init 运行时静态方法不可用
staticmethod not available when init runs
我意识到我无法从其 __init__
方法调用 class' 静态方法。
class c():
def __init__(self):
f()
@staticmethod
def f():
print("f called")
c()
给出一个NameError: name 'f' is not defined
.
为什么找不到静态方法?
由于f()
是class的一个方法,您可以使用c.f()
或self.f()
来调用它
class c():
def __init__(self):
#Call static method using classname
c.f()
#Call static method using self
self.f()
@staticmethod
def f():
print("f called")
c()
那么输出将是
f called
f called
类似于在class之外调用静态方法,我们可以使用ClassName
或Instance
#Using classname to call f
c.f()
#Using instance to call f
c().f()
输出将是
f called
f called
这仅仅是因为 Python 在您这样引用它时正在全局命名空间中搜索一个名为 f
的函数。
要引用 class' f
方法,您需要确保 Python 在适当的命名空间中查找。只需在前面加上 self.
.
class c():
def __init__(self):
self.f() # <-
@staticmethod
def f():
print("f called")
c()
结果
f called
我意识到我无法从其 __init__
方法调用 class' 静态方法。
class c():
def __init__(self):
f()
@staticmethod
def f():
print("f called")
c()
给出一个NameError: name 'f' is not defined
.
为什么找不到静态方法?
由于f()
是class的一个方法,您可以使用c.f()
或self.f()
来调用它
class c():
def __init__(self):
#Call static method using classname
c.f()
#Call static method using self
self.f()
@staticmethod
def f():
print("f called")
c()
那么输出将是
f called
f called
类似于在class之外调用静态方法,我们可以使用ClassName
或Instance
#Using classname to call f
c.f()
#Using instance to call f
c().f()
输出将是
f called
f called
这仅仅是因为 Python 在您这样引用它时正在全局命名空间中搜索一个名为 f
的函数。
要引用 class' f
方法,您需要确保 Python 在适当的命名空间中查找。只需在前面加上 self.
.
class c():
def __init__(self):
self.f() # <-
@staticmethod
def f():
print("f called")
c()
结果
f called