Talk Is Cheap, Show Me The Code.
定义两个类,分别存在函数返回int值
class Item:
@classmethod
def get_length(self):
return 18
class Date:
def get_date(self):
return 5
输出Item中的get_length
print(Item.get_length())
>>> 18
输出Date中的get_date
print(Date.get_date())
>>> Exception has occurred: TypeError get_date() missing 1 required positional argument: 'self'
对Date进行初始化后再输出get_date
date = Date()
print(date.get_date())
>>> 5
总结: 类中函数被@classmethod装修无需初始化, 否则需要。