【发布时间】:2018-10-18 17:22:03
【问题描述】:
如果func 是一个全局函数,func 可以自己引用它。
def func(y):
result = func.x + y
# `func.x` does not raise an errors
return result
func.x = 5
func(100)
但是,类方法似乎不能引用自身:
class K:
def mthd(self, y):
return mthd.x + y
mthd.x = 5
K.mthd() # raises an exception
引发的异常是NameError:
[Drive Letter]:\[path]
Traceback (most recent call last):
File "[Path]/[filename].py", line 35, in <module>
K.mthd()
File "[Path]/[filename].py", line 40, in mthd
return mthd.x + y
NameError: name 'mthd' is not defined
Process finished with exit code 1
这是为什么?
是因为"func" 在globals 而"mthd" 在K.__dict__ 中吗?
函数可以引用自身之外的变量,例如:
x = 3
def f():
print(x)
错误是因为K.mthd 可以访问名称locals 和globals,但不能访问K.__dict__?
【问题讨论】:
标签: python python-3.x class oop