类方法classmethod
#类方法通过@classmethod 装饰器实现
# 类方法和普通方法的区别是,类方法只能访问类变量,不能访问实例变量
class Dog():
name = "stupid_dog"
def __init__(self,name):
self.name = name
@classmethod
def eat(self):
print("classmethod中的self--->",self) # <class '__main__.Dog'>
print("%s is eating"%self.name)
@classmethod
def run(cls):
print(cls)
# self.name先访问实例变量,在访问类变量
# 类方法只能访问类变量,不能访问实例变量
# 原因:因为self这个参数接受的不是实例本身,而是类本身
dog = Dog("MJJ")
dog.eat()
dog.run()
print(Dog) # <class '__main__.Dog'>
运行结果:
classmethod中的self---> <class '__main__.Dog'>
stupid_dog is eating
<class '__main__.Dog'>
<class '__main__.Dog'>