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装修无需初始化, 否则需要。
本文通过示例介绍了Python中类方法和实例方法的区别。类方法`get_length`在类`Item`中可以直接调用,无需实例化对象。而实例方法`get_date`在`Date`类中必须先创建对象后才能调用。理解这些差异对于Python面向对象编程至关重要。
11万+

被折叠的 条评论
为什么被折叠?



