第13章 面向对象编程(7)

理解Python中的静态方法与类方法
本文深入探讨了Python编程中静态方法和类方法的区别与用法,通过实例展示了如何使用@staticmethod和@classmethod装饰器,并解释了类方法必须传入一个cls参数的重要性。

13.8 静态方法和类方法

13.8.1 staticmethod()和classmethod()内建函数

>>> class C(object): ... def M1(self): ... pass ... >>> C.M1() Traceback (most recent call last): File "<interactive input>", line 1, in <module> TypeError: unbound method M1() must be called with C instance as first argument (got nothing instead) >>> C().M1() >>>
>>> class TestStaticMethod: ... @staticmethod ... def foo(): ... print 'calling static method foo()' ... >>> TestStaticMethod.foo() calling static method foo() >>> class TestClassMethod(object): ... @classmethod ... def foo(cls): ... print 'calling class method foo()' ... print 'foo() is a part of class ', cls.__name__ ... >>> TestClassMethod.foo() calling class method foo() foo() is a part of class TestClassMethod >>>
类方法必须传入一个cls参数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值