Python classmethod staticmethod 进价学习

本文详细解析了Python中@classmethod和@staticmethod装饰器的用途与区别。介绍了如何利用这两种装饰器来优化代码结构,降低资源消耗,并通过实例说明了它们的工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@classmethod means: when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods). This means you can use the class and its properties inside that method rather than a particular instance.

@staticmethod means: when this method is called, we don't pass an instance of the class to it (as we normally do with methods). This means you can put a function inside a class but you can't access the instance of that class (this is useful when your method does not use the instance).


When an instance attribute is referenced that isn’t a data attribute, its class is searched. 

If the name denotes a valid class attribute that is a function object, a method object is 
created by packing (pointers to) the instance object and the function object just found together
in an abstract object: this is the method object. When the method object is called with an 
argument list, a new argument list is constructed from the instance object and the argument list, 

and the function object is called with this new argument list.


类方法:
classmethod 是类对象与函数的结合。
可以使用类和类的实例调用,但是都是将类作为隐含参数传递过去。
使用类来调用 classmethod 可以避免将类实例化的开销。


类的静态方法:
当一个函数逻辑上属于一个类又不依赖与类的属性的时候,可以使用staticmethod。
使用 staticmethod 可以避免每次使用的时都会创建一个对象的开销。
staticmethod 可以使用类和类的实例调用。但是不依赖于类和类的实例的状态。


实例方法:
instance method 就是实例对象与函数的结合。
使用类调用,第一个参数明确的传递过去一个实例。
使用实例调用,调用的实例被作为第一个参数被隐含的传递过去。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值