首页 > 文章列表 > python类方法的注意点

python类方法的注意点

Python 类方法
435 2022-08-07

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()