class People(object):
country = 'china'
def __init__(self,name):
self.country = name
def getCountry(self): # -- 实例方法
return self.country
#类方法,用classmethod来进行修饰
@classmethod
def getCountry(cls): # -- 类方法
return cls.country
p = People('aodaliya')
print(p.getCountry()) #可以用过实例对象引用 # 同名方法时,类方法会覆盖实例方法
# print(People.getCountry()) #可以通过类对象引用
本文介绍了Python中类方法和实例方法的区别与使用方式。通过一个简单的例子展示了如何定义类方法并通过类对象或实例对象调用它。同时指出当类中存在同名的方法时,类方法会覆盖实例方法。

291

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



