【发布时间】:2019-08-06 06:51:08
【问题描述】:
最近我注意到一个新概念:python3 中的class function。
(注意:不是问类方法,而是下一个代码中类似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(最近一次调用最后一次):文件“a.py”,第 9 行,在
A.fun() TypeError: unbound method fun() must be called with A instance as first argument (什么都没有)
python3 输出:
有趣
有趣2
而且,在python3中,它似乎被称为类函数,它不再是一个方法。
所以,我的问题是:为什么会发生这种变化?因为我们已经可以使用@staticmethod 在类中定义一些实用函数。
【问题讨论】:
-
当然,我仍然可以使用静态方法,只是我怕我会错过一些新功能,就像关于“类方法和静态方法”比较的老问题一样。最后,我们都知道我们可以使用类方法来创建静态方法不能创建的工厂方法。那么现在这个比较如何呢?
标签: python python-3.x