python类方法的注意点

python类方法的注意点

1、@classmethod必须在方法上面。

2、第一个cls必须有,指的是类对象本身。

3、在类方法中访问实例属性和实例方法会导致错误。

4、当子类继承父类方法时,cls是子类对象,而不是父类对象。

调用类方法格式:“类名.类方法名(参数列表)”。

参数列表中不与要也不能cls传值。

实例

classPerson:

#类属性

school="中加枫华国际学校"

tuition=100000

count=0

#实例属性

def__init__(self,name,age,gender):

self.name=name

self.age=age

self.gender=gender

Person.count=Person.count+1

@classmethod

defprintSchool(cls):

print(cls)

print(cls.school)

#实例方法

defget_score(self):

print("姓名:{0};年龄:{1};性别:{2}".format(self.name,self.age,self.gender))

stu1=Person("sue",22,"male")

stu1.get_score()

Person.printSchool()

以上内容为大家介绍了python培训之类方法的注意点,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注我们

推荐阅读