Python基础–类方法和静态方法
类方法
- 类对象所拥有的方法
- 需要使用
classmethod
来标识其为类方法
- 第一个参数必须是对象
- 一般以
cls
最为第一个参数
场景说明:
类方法和实例方法对比,类方法并不依赖实例对象
可以在没有实例对象的情况下,完成对类属性的处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class Dog: type = "狗"
@classmethod def get_info(cls): print("类型是: %s"% cls.type)
# 调用类方法,类对象/实例对象都可以使用 Dog.get_info()
# 调用对象方法必须是需要有实例属性才能够被调用 dog1 = Dog() dog1.get_info()
|
静态方法
- 需要使用装饰器
staticmethod
进行修饰
- 默认情况下,静态方法既不传递类对象也不传递实例对象(形参没有
self/cls
)
- 静态方法可以通过实例对象和类对象去访问
场景说明:
当方法中既不需要使用实例对象,也不需要使用类对象的时候,可以定义静态方法
取消不需要的参数传递,有利于减少不必要的内存占用和性能消耗
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class Cat:
@staticmethod # @staticmethod标识的方法为静态方法 # 静态方法既不传递实例对象,也不传递类对象(稍微节省性能) def eat(): print("爱吃鱼")
def drink(self): print("喝水") # 使用实例对象调用静态方法 Cat.eat() cat1 = Cat() # 使用类对象进行调用静态方法 cat1.eat()
|
对象方法,类方法和静态方法的调用顺序
==类中同时定义了同样的对象方法,类方法和静态方法时,.会优先调用最后一个定义的方法==
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Cat: def eat(self): print("对象")
@classmethod def eat(cls): print("类")
@staticmethod # @staticmethod标识的方法为静态方法 # 静态方法既不传递实例对象,也不传递类对象(稍微节省性能) def eat(): print("静态")
# 使用实例对象调用静态方法 Cat.eat() cat1 = Cat() # 使用类对象进行调用静态方法 cat1.eat()
|