我在http://pydanny.com/python-dictionary-as-a-class.html處發現了以下代碼。代碼工作正常,我有點理解爲什麼它只是一個類似的代碼,在它下面給出錯誤。在Python中實現類作爲字典
def newclass(**kwargs):
""" Use kwargs.update() method to handle inheritance """
def set(key, value):
""" Sets key/value to the kwargs.
Replicates self/this clumsily
"""
kwargs[key] = value
kwargs['set'] = set
return kwargs
我試代碼:
def closing():
x=1
def closed():
print(x)
x=x+1
return(closed)
a=closing()
a()
錯誤消息:
Traceback (most recent call last):
File "<pyshell#606>", line 1, in <module>
a()
File "<pyshell#604>", line 4, in closed
print(x)
UnboundLocalError: local variable 'x' referenced before assignment
當我使用 '非本地X' 在它工作的封閉功能,但怎麼來的初始代碼作品,未經「外地」。 我的理解是,它是一個閉包,內部函數將保持外部(自由)變量的引用,並且無論何時調用內部函數,它都能夠對該閉合變量進行操作,但當然我還沒有理解它的某些部分正常。 請幫我清除我缺少的概念。 謝謝所有回答的人。 SO太有幫助了。
它看起來好像你的第一個片段有空白錯誤 – hdgarrood