Just recently I noticed a new concept: class function
in python3.
(NOTE: not ask class method, but class function like fun
in next code.)
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}
If execute above code:
python2 output:
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 output:
fun
fun2
And, in python3, it seems been called as class function, it's no longer a method.
So, my question is: why this changes? As we could already define some utility function in class using @staticmethod
.