2011-10-06 7 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으로 설정하는 것이 좋습니다. 그렇지 않으면 오류가 발생합니다.

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

이 당신이 뭘 하려는지이다 : 나는 일반적으로 __init__에 그렇게?

#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()