为什么用类名无法调用类方法,却可以调用变量?
class Person(object): count = 0 def __init__(self,name,score): self.name = name self.score = score def get_grade(self): return 'A' p1 = new Person('Bom',90) print p1.get_grade() print Person.get_grade() print Person.count print p1.count
最佳回答
2019-09-19你这个不是类方法,忘了写@calssmethod了
python类中定义的变量和方法都分为类变量和实例变量,类方法和实例方法,类变量和类方法是绑定与类中的,它们可以被所有的类实例共享,通过类名和实例名都可以调用;而实例变量和实例方法是与实例绑定的,只能通过实例名调用,无法通过类名调用实例方法。