2017-09-19 1 views
0

저는 Python을 처음 사용합니다. 개체를 만들 수있는 클래스를 만들려고합니다. 개인 변수 인스턴스를 사용하여 개수를 추적합니다. 내 코드 - NameError : name 's'이 (가) 정의되지 않았습니다.

class s: 
    __instance=2 

    if s.__instance<2: 
     def __init__(self,x): 
      s._instance = x 
      s._instance = s._instance+1 
      print(s._instance) 

a=s(5) 

내가 가지고 코드를 실행

-

"C:\Users\PIYU\AppData\Local\Programs\Python\Python36\python.exe" 
"C:/Users/PIYU/PycharmProjects/PythonProgram/singleton.py" 
    Traceback (most recent call last): 
    File "C:/Users/PIYU/PycharmProjects/PythonProgram/singleton.py", line 1, in <module> 
    class s: 
    File "C:/Users/PIYU/PycharmProjects/PythonProgram/singleton.py", line 4, in s 
    if s.__instance<2: 
    NameError: name 's' is not defined 
+0

만 문법 설탕하지만 난 지금 하나를 찾을 수 없습니다 - :

이 상황이 명확하게하려면 누군가가 질문을 끝내시기 바랍니다. –

+0

관련 [documentation] (https://docs.python.org/3/tutorial/classes.html#class-definition-syntax). –

+0

@ bruno desthuilliers 모든면에서 나는 모든 비슷한 질문을 던졌다. 내가 물었던 대답을 찾지 못했을 때 –

답변

5

이 실제로 정의되기 전에, 그것의 자신의 정의에 s을 참조하려고하기 때문에 오류입니다. 그 전에 대신 __init__에서 그 조건을 사용하려고합니다.

+0

@AlexanderReynolds가 OP가하려고하는 것에 대해, 클래스 속성을 사용하는 것이 이치에 맞습니다. –

1

파이썬에서 class은 새로운 class 클래스 개체를 만들고이를 포함 범위의 클래스 이름에 바인딩하는 실행 문입니다. 전체 문이 실행될 때까지 (IOW, class 문 블록까지) 클래스 개체는 존재하지 않으며 이름이 정의되지 않습니다.

class Foo(object): 
    bar = 42 
    def foo(self): 
     print "foo" 

실제로 그것은 여기 꽤 몇 가지 다른 질문의 중복입니다

def foo(self): 
    print "foo" 

Foo = type("Foo", (object,), {"foo": foo, "bar": 42}) 
del foo # remove the name from current scope 
+0

나는 내부에서 클래스를 참조하는 것이 여전히 가능하다고 믿는다. 블록 내부의 명령문을 순서대로 조심해야한다. [예 :] (http://code.activestate.com/recipes/52558-the-singleton-pattern-implemented-with-python/) –

+0

@AlexanderReynolds 메소드 내에서 클래스를 참조 할 수 있습니다. 'class' 문 블록, period 내에서이를 __can 참조 할 수 없습니다. –

+0

아, class 블록 범위가 메서드로 확장되지 않습니다. –

관련 문제