2014-04-22 3 views
1

파이썬에서 장난감 싱글 톤을 만들어 언어의 내용을 배우고 파이썬의 작동 방식에 문제가 생기고 있습니다. 나는 예를 정적으로 널 할당 할 수 없습니다해야, 무슨 일이야파이썬에서 언 바운드 변수

File "/home/paul/projects/peachpit/src/ErrorLogger.py", line 7, in getInstance 
    if instance is None : 
UnboundLocalError: local variable 'instance' referenced before assignment 

를 얻을이

class ErrorLogger: 
    # Singleton that provides logging to a file 
    instance = None 

    def getInstance(): 
    # Our singleton "constructor" 
    if instance is None : 
     print "foo" 

같은 클래스가 나는

log = ErrorLogger.getInstance() 

로를 호출 할 때 선언? 이것을하는 올바른 방법은 무엇입니까?

+0

당신이 사용할 수있는'@ staticmethod' 또는 아주 잘 설명되어 있습니다 둘 다'@의 clsmethod' : http://stackoverflow.com/questions/136097/what-is-the-difference-between- staticmethod-and-class-method-in-python – SimonT

답변

5

정적 변수이므로 접두사 ErrorLogger으로 전화해야합니다.

class ErrorLogger: 
    # Singleton that provides logging to a file 
    instance = None 

    @staticmethod 
    def getInstance(): 
    # Our singleton "constructor" 
    if ErrorLogger.instance is None : 
     print "foo" 
+0

@classmethod를 사용할 수도 있습니다. 차이점은 미묘하지만 여전히 있습니다. – fr1tz

+0

'@ classmethod'의 장점은 클래스를 메서드에 대한 인수로 가져 오는 것이므로이를 사용하여 직접적으로 함수를 가져올 수 있습니다 :'@classmethod def getInstance (cls) : if cls.instanece is None : ...' – Blckknght