func
can refer it itself if func
is a global function.
def func(y):
result = func.x + y
# `func.x` does not raise an errors
return result
func.x = 5
func(100)
However, it seems that a class method cannot refer to itself:
class K:
def mthd(self, y):
return mthd.x + y
mthd.x = 5
K.mthd() # raises an exception
The exception raised is a 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
Why is this?
Is it because "func"
is in globals
whereas "mthd"
is in K.__dict__
?
functions can refer to variables outside of themselves, such as:
x = 3
def f():
print(x)
Is the error caused because K.mthd
has access to the names locals
and globals
, but not K.__dict__
?