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

被折叠的 条评论
为什么被折叠?



