[英]NameError : name 's' is not defined
我是Python的新手。 我正在嘗試創建一個僅允許創建對象的類。 我正在使用一個私有變量實例來跟蹤計數。 我的代碼-
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
這個錯誤是因為你正在嘗試引用s
在它自己的定義,實際上是定義之前。 我會嘗試在__init__
而不是之前使用該條件。
在Python中, 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.