最近我注意到一个新概念:python3 中的类函数
。
(注意:不是询问类方法,而是询问类函数,例如下一个代码中的 fun
。)
class A:
def fun():
print("fun")
@staticmethod
def fun2():
print("fun2")
A.fun()
A.fun2()
# updated
print(A.__dict__)
# {'__module__': '__main__', 'fun': <function A.fun at 0x0000014C658F30D0>, 'fun2': <staticmethod object at 0x0000014C658E1C50>, '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}
如果执行上面的代码:
python2 输出:
Traceback (most recent call last): File "a.py", line 9, in
A.fun() TypeError: unbound method fun() must be called with A instance as first argument (got nothing instead)
python3 输出:
fun
fun2
而且,在python3中,它似乎被称为类函数,它不再是一个方法。
所以,我的问题是:为什么会发生这种变化?因为我们已经可以使用 @staticmethod
在类中定义一些实用函数。
最佳答案
这是因为 python 3 类中的所有函数默认都具有静态行为。 Python 3 放弃了未绑定(bind)方法的概念。类的所有成员方法都可以使用类对象本身来调用,就像您所做的那样。
因此,除了您的代码之外,还允许使用以下代码:
class A:
def func(self):
print('Hello')
A.func(123)
这样做可能是为了方便,让您不必编写 @staticmethod
在某些情况下,还可以让您将实例方法与其他类型的对象重用,如上面的代码片段所示。
该函数未显示为静态方法,因为它不是。正如 @Aran-Fey 指出的那样,无参数静态方法仍然可以在类的实例上调用,这就是为什么我们有 @staticmethod
在 Python 3 中。
(请检查编辑历史记录以查找此答案的旧版本、错误版本)
关于python - python 类中的所有方法都表现得像静态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55178404/