Python中的类方法和静态

本文详细解释了Python中类方法、静态方法与普通方法的区别,通过实例展示了它们的调用方式及特点。

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

原文:http://clojure.cn/python中的类方法和静态/

转载自: http://www.tuicool.com/articles/yqmm6fu


这也不是什么难点,写一下就是感觉网上有些写得不太明白,其实不用多深入探讨,可以简单的知道区别只有如下即可:

1,普通方法须用对象调用,默认第一个参数会传入对象自身(这个“自身”习惯上用一个名为self的变量表示,其实无所谓名字,虽然贫道并不推荐改成其他)。

2,类方法可以使用对象或者类调用,类似普通方法,默认第一个参数传入类方法所在的类而不是对象(同上习惯上用cls表示)。

3,静态方法可以使用对象或者类调用,并没有默认传入的方法。

下面看个例子:

class Demo(object):
  def regular_method(self, arg, *args, **kwargs):
    print self, id(self), arg, args, kwargs
  @classmethod
  def class_method(cls, arg, *args, **kwargs):
    print cls, id(cls), arg, args, kwargs
  @staticmethod
  def static_method(arg, *args, **kwargs):
    print arg, args, kwargs
demo = Demo()
demo.regular_method("a", "b", c = "c")
demo.class_method("a", "b", c = "c")
Demo.class_method("a", "b", c = "c")
demo.static_method("a", "b", c = "c")
Demo.static_method("a", "b", c = "c")

输出还是很明白的,不多说了:

<__main__.Demo object at 0x7f4f41e47c90> 139978384637072 a (‘b’,) {‘c’: ‘c’}

<class ‘__main__.Demo’> 15255136 a (‘b’,) {‘c’: ‘c’}

<class ‘__main__.Demo’> 15255136 a (‘b’,) {‘c’: ‘c’}

a (‘b’,) {‘c’: ‘c’}

a (‘b’,) {‘c’: ‘c’}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值