python 静态方法与类方法
来源:互联网 发布:淘宝旺铺基础版店招 编辑:程序博客网 时间:2024/05/23 13:37
1. 对象方法有self参数,类方法有cls参数,静态方法是不需要这些附加参数的。
2. @staticmethod和@classmethod都是用来定义静态函数的。
相同点:
都不用实例化类,可以直接用类名来调用其相关属性。
不同点:
@classmethod的第一个参数是cls,因此可以访问类变量,或是用作类厂。
@staticmethod只是自身代码在类里面,对类的其它再无相关。
3. 一般情况下用@classmethod,@staticmethod只适用于不想定义全局函数的情况。
4. 类方法可以访问per-class的数据。举个不实际的例子:
- >>> class Named(object):
- ... @classmethod
- ... def name(cls):
- ... return cls.__name__
- ...
- >>> class Sub(Named):
- ... pass
- ...
- >>> obj = Sub()
- >>> obj.name()
- 'Sub'
- ------------------------------------------------------------------------------------------------------------------------------
- 第一种方式(staticmethod):
- >>> class Foo:
- str = "sample."
- def bar():
- print Foo.str
- bar = staticmethod(bar)
- >>> Foo.bar()
- sample.
- 第二种方式(classmethod):
- >>> class Foo:
- str = "sample."
- def bar(cls):
- print cls.str
- bar = classmethod(bar)
- >>> Foo.bar()
- sample.
- ---------------------------------------------------------------
- 上面的代码我们还可以写的更简便些:
- >>> class Foo:
- str = "sample."
- @staticmethod
- def bar():
- print Foo.str
- >>> Foo.bar()
- sample.
- 或者
- >>> class Foo:
- str = "sample."
- @classmethod
- def bar(cls):
- print cls.str
- >>> Foo.bar()
- sample
- <p> </p>
- [总结]python 静态方法与类方法
- python 静态方法与类方法
- Python类成员方法与静态方法
- Python类的成员方法、类方法与静态方法
- python中的静态类与方法
- Python 静态类、静态方法
- Python 静态方法 类方法
- Python 静态方法 类方法
- Python 类方法 静态方法
- Python中静态方法与类方法比较
- python中的类方法与静态方法的区别
- python类方法、实例方法、静态方法
- Python 静态方法 类方法 实例方法
- python实例方法,静态方法,类方法
- python --类方法、对象方法、静态方法
- Python:类方法、静态方法、实例方法
- Python普通方法、静态方法、类方法
- python --类方法、对象方法、静态方法
- CxImage
- linux内核tcp的定时器管理(二)
- 第十三章 字符串
- HDU-4622-Reincarnation
- 前端UI,javascript,css框架集合
- python 静态方法与类方法
- 第十四章 类型信息
- UVA 11076 - Add Again
- linux内核中tcp连接的断开处理
- Tomcat中文编码
- 谈30岁后it人员职业发展规划
- HDU-4632-Palindrome subsequence
- 您对孩子说了这六句话了吗?
- HDU 3371 Connect the Cities MST存在已建好的边