两者都不需要实例化,就能调用类方法
@staticmethod不需要传参
@classmethod需要传入cls
# _*_ coding:utf_8 _*_
class People:
def hello(self):
print("hello, Everyone.")
@staticmethod
def say_morning():
print("good morning")
# print(People.hello()) 这里会报错!
@classmethod
def say_afternoon(cls):
print("good afternoon")
print(cls().hello())
# 实例化一个对象
LiMing = People()
LiMing.hello()
People.say_morning()
People.say_afternoon()
"""""""""""""""""""
这里是输出:
hello, Everyone.
good morning
good afternoon
hello, Everyone.
"""""""""""""""""""
另一个例子
class A(object):
bar = 1
def func1(self):
print('foo')
@classmethod
def func2(cls):
print('func2')
print(cls.bar)
cls().func1() # 调用 foo 方法
A.func2() # 不需要实例化
参考
https://blog.csdn.net/anshiquanshu/article/details/108482180