2011-10-06 125 views
3

尋找如何讓一個方法/函數在一個類中可以訪問同一類中的另一個方法/函數所設置的變量,而不必在外部執行多餘的(和有問題的代碼) 。Python 3:在一個類中的方法之間共享變量

這裏是行不通的例子,但可以告訴你什麼是我想要做的事:

#I just coppied this one to have an init method 
class TestClass(object): 

    def current(self, test): 
     """Just a method to get a value""" 
     print(test) 
     pass 

    def next_one(self): 
     """Trying to get a value from the 'current' method""" 
     new_val = self.current_player.test 
     print(new_val) 
     pass 
+2

在同一個班級中,還是在同一個對象中? –

+1

對於那些無法閱讀[教程](http://docs.python.org/py3k/tutorial/)的人,我感到抱歉... – JBernardo

回答

8

你在一個方法對其進行設置,然後看看它在另一個:

class TestClass(object): 

    def current(self, test): 
     """Just a method to get a value""" 
     self.test = test 
     print(test) 

    def next_one(self): 
     """Trying to get a value from the 'current' method""" 
     new_val = self.test 
     print(new_val) 

請注意,在嘗試檢索它之前,您需要設置self.test。否則,它會導致錯誤。我一般在__init__這麼做:

class TestClass(object): 

    def __init__(self): 
     self.test = None 

    def current(self, test): 
     """Just a method to get a value""" 
     self.test = test 
     print(test) 

    def next_one(self): 
     """Trying to get a value from the 'current' method""" 
     new_val = self.test 
     print(new_val) 
+0

@Amber謝謝你的錯誤。 – cwallenpoole

0

這就是你想要做的嗎?

#I just coppied this one to have an init method 
class TestClass(object): 

    def current(self, test): 
     """Just a method to get a value""" 
     print(test) 
     self.value = test 
     pass 

    def next_one(self): 
     """Trying to get a value from the 'current' method""" 
     new_val = self.value 
     print(new_val) 
     pass 

a = TestClass() 
b = TestClass() 
a.current(10) 
b.current(5) 
a.next_one() 
b.next_one()