本篇内容主要讲解“python类方法的注意点有哪些”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“python类方法的注意点有哪些”吧!
1、@classmethod必须在方法上面。
2、第一个cls必须有,指的是类对象本身。
3、在类方法中访问实例属性和实例方法会导致错误。
4、当子类继承父类方法时,cls是子类对象,而不是父类对象。
调用类方法格式:“类名.类方法名(参数列表)”。
参数列表中不与要也不能 cls 传值。
实例
class Person:
# 类属性
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
def printSchool(cls):
print(cls)
print(cls.school)
# 实例方法
def get_score(self):
print("姓名:{0};年龄:{1};性别:{2}".format(self.name,self.age,self.gender))
stu1 = Person("sue", 22, "male")
stu1.get_score()
Person.printSchool()
到此,相信大家对“python类方法的注意点有哪些”有了更深的了解,不妨来实际操作一番吧!这里是天达云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!