簡體   English   中英

NameError:名稱“ s”未定義

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM