我有一個Python應用程序,如下所示:Python - 爲什麼這個類的變量沒有在方法中定義?
global_counter = 0
connections = {}
class SocketHandler():
currentid = 0
def open(self):
global global_counter
global connections
currentid = global_counter
global_counter += 1
connections[currentid] = self
print "WebSocket " + str(currentid) + " opened"
def on_close(self):
global connections
print "WebSocket " + str(currentid) + " closed"
del connections[currentid]
,我發現了錯誤:
NameError: global name 'currentid' is not defined
上的線「開」和「on_close」在那裏我打印,我打開/關閉連接。我在課堂上定義它,爲什麼它不在範圍內。另外,我已經讀過使用全局變量是不好的,但我沒有看到解決這個問題的方法。有人能指出我應該做什麼嗎?謝謝。
使用self.currentid –