[英]How to get updated variable by a python function from another python function?
我正在嘗試通過python方法訪問更新的初始化變量,以訪問同一類中的另一個python方法。 下面是我的示例代碼塊。
class test(object):
def __init__(self):
self.a = []
def test1(self):
self.a = [1,2,3,4,5]
print ("Output of test1 #", self.a)
def test2(self):
print ("Output of test2 #",self.a)
test().test1()
test().test2()
Output # Output of test1 # [1, 2, 3, 4, 5]
Output of test2 # []
我的理解是,如果我在__ init __(self)節中初始化變量,則可以從類中的方法更新相同的變量,並可以從同一類的另一方法訪問相同的變量。 如果我的理解是錯誤的,請糾正我。
您想要的單詞不是method
,而是module
。
您的理解是正確的,但僅適用於同一實例-並且您正在創建兩個實例:
test().test1()
# ^- just created a new instance of test
test().test2()
# ^- just created another, different instance of test
您想要的是:
test_instance = test()
test_instance.test1()
test_instance.test2()
由於test()。test1()和test()。test2()是兩個不同的對象。 我認為您應該閱讀有關Python OPP的更多信息: https : //docs.python.org/2/tutorial/classes.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.