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学习教程请关注IT培训机构:千锋教育。

申请14天超长免费试听资格
获取500G教程资料
姓名
电话
课程
立即申请