类可以有类属性,也可以有类方法,类方法主要是对类属性的封装。是类对象所拥有的方法,需要用修饰器@classmethod来标识其为类方法,对于类方法,第一个参数必须是类对象,一般以cls作为第一个参数(当然可以用其他名称的变量作为其第一个参数,但是大部分人都习惯以'cls'作为第一个参数的名字,就最好用'cls'了),能够通过实例对象和类对象去访问。
类方法:
class People(object):
#类属性 __country = 'china'
def __init__(self): self.name = "Edward"
#类方法,用classmethod来进行修饰 @classmethod def getCountry(cls): return cls.__country
# 类方法,用classmethod来进行修饰 @classmethod def setCountry(cls,country): cls.__country = country
#类方法不可使用实例属性 #类方法只能访问类属性 #@classmethod #def showPerson(cls): # print(name)
p = People() print(p.getCountry()) #可以用过实例对象引用 print(People.getCountry()) #可以通过类对象引用 print("----------------") p.setCountry("USA") print(p.getCountry()) #可以用过实例对象引用 print(People.getCountry()) #可以通过类对象引用
#p.showPerson() |
静态方法:
需要通过修饰器@staticmethod来进行修饰,静态方法不需要多定义参数.
class People(object): country = 'china'
@staticmethod #静态方法 def getCountry(): return People.country
#静态方法不可访问实例属性 #静态方法可以访问类属性 #通过对象可以访问静态方法 #通过类也可访问静态方法 print(People.getCountry()) person = People() print(person.getCountry()) |
总结:
|