python - 關于函數調用的問題
問題描述
def test1(): a = 1 b = 2 def test2(): c = 3 d = c + a print(d)test2這邊想實現下面的test2調用上面test1里面的數據,要怎么實現,使用的是python3
問題解答
回答1:首先,你這種需求是不可能且不合理的,兩個分立的函數不可能相互訪問里面的變量的
如果用閉包倒是可以做到,不過不知道是不是你想要的:
def test1(): a = 1 b = 2 def test2():c = 3d = c + aprint(d) return test2test2 = test1()test2()回答2:
可以將test1封裝為一個類
#-*-coding:utf8-*-class test1(): '''docstring for test1''' def __init__(self):self.a=0self.b=0self.test1() def test1(self):self.a=1self.b=2test = test1()def test2(): c=3 d=c+test.a print (d)test2()
初始化可以放在你想調用的位置,并且在初始化的時候默認調用了test1()方法,這樣就可以通過類的對象訪問數據了。
回答3:可以讓test1用return來返回a和b的值:
def test1(): a = 1 b = 2 return a,bdef test2(): c = 3 a,b = test1() d = c + a print(d)test2()回答4:
哈哈,都是人才,閉包、封類、明確返回,以上每一個都是獨立的解決辦法。
相關文章:
1. javascript - 有適合開發手機端Html5網頁小游戲的前端框架嗎?2. javascript - 關于apply()與call()的問題3. python 利用subprocess庫調用mplayer時發生錯誤4. python - Pycharm的Debug用不了5. python - pandas按照列A和列B分組,將列C求平均數,怎樣才能生成一個列A,B,C的dataframe6. html - eclipse 標簽錯誤7. 安全性測試 - nodejs中如何防mySQL注入8. javascript - nginx反向代理靜態資源403錯誤?9. python - pycharm 自動刪除行尾空格10. python文檔怎么查看?
