class People(object):
country = 'china'
#类方法,用classmethod类进行修饰
@classmethod
def getCountry(cls):
return cls.country
p = People()
print(p.getCountry())
print(People.getCountry())
类方法:能够通过实例对象和类对象去访问类属性
类方法还有一个用途
class People(object):
country = 'china' #类属性
#类方法,用classmethod来进行修饰
@classmethod
def getCountry(cls):
return cls.country
@classmethod
def setCountry(cls,country):
cls.country = country
p = People()
p.setCountry('japan') #实例属性
print(p.getCountry())
print(People.getCountry())
静态方法
需要通过修饰器@staticmethod来进行修饰,静态方法不需要多定义参数
class People(object):
country = 'china'
@staticmethod
#静态方法
def getCountry():
return People.country
p = People()
print(p.getCountry())
print(People.getCountry())
会报错
class People(object):
country = 'china'
def getCountry():
return People.country
print(People.getCountry)
网友评论