python中的静态方法和类方法
2016-08-18 19:03
387 查看
静态方法实际上就是普通函数,定义形式是在def行前加修饰符@staticmethod,只是由于某种原因需要定义在类里面。静态方法的参数可以根据需要定义,不需要特殊的self参数。可以通过类名或者值为实例对象的变量,已属性引用的方式调用静态方法
类方法定义形式是在def行前加修饰符@classmethod,这种方法必须有一个表示其调用类的参数,一般用cls作为参数名,还可以有任意多个其他参数。类方法也是类对象的属性,可以以属性访问的形式调用。在类方法执行时,调用它的类将自动约束到方法的cls参数,可以通过这个参数访问该类的其他属性。通常用类方法实现与本类的所有对象有关的操作。
实例方法隐含的参数为类实例,而类方法隐含的参数为类本身。
静态方法无隐含参数,主要为了类实例也可以直接调用静态方法。
所以逻辑上类方法应当只被类调用,实例方法实例调用,静态方法两者都能调用。
在贴一例,供参考:
类方法定义形式是在def行前加修饰符@classmethod,这种方法必须有一个表示其调用类的参数,一般用cls作为参数名,还可以有任意多个其他参数。类方法也是类对象的属性,可以以属性访问的形式调用。在类方法执行时,调用它的类将自动约束到方法的cls参数,可以通过这个参数访问该类的其他属性。通常用类方法实现与本类的所有对象有关的操作。
##coding:utf-8 class TestClassMethod(object): METHOD = 'method hoho' def __init__(self): self.name = 'leon' def test1(self): print 'test1' print self @classmethod def test2(cls): print cls print 'test2' print TestClassMethod.METHOD print '----------------' @staticmethod def test3(): print TestClassMethod.METHOD print 'test3' a = TestClassMethod() a.test1() a.test2() a.test3() TestClassMethod.test3()
test1 <__main__.TestClassMethod object at 0x0000000003DDA5F8> <class '__main__.TestClassMethod'> test2 method hoho ---------------- method hoho test3 method hoho test3
实例方法隐含的参数为类实例,而类方法隐含的参数为类本身。
静态方法无隐含参数,主要为了类实例也可以直接调用静态方法。
所以逻辑上类方法应当只被类调用,实例方法实例调用,静态方法两者都能调用。
在贴一例,供参考:
class TestClassMethod(object): METHOD = 'method hoho' def __init__(self): self.name = 'leon' def test1(self): print 'test1' print self @classmethod def test2(cls): print cls print 'test2' print TestClassMethod.METHOD print '----------------' @staticmethod def test3(): print TestClassMethod.METHOD print 'test3' a = TestClassMethod() a.test1() a.test2() a.test3() TestClassMethod.test3()
test1 <__main__.TestClassMethod object at 0x0000000003DDA5F8> <class '__main__.TestClassMethod'> test2 method hoho ---------------- method hoho test3 method hoho test3
相关文章推荐
- Python中静态方法的实现
- python基础3--面向对象--类变量、实例变量、类方法、静态方法、实例方法
- Python 静态方法和静态类
- Python中的静态方法-pybatis的准备阶段(五)
- [Python]静态方法和类方法
- Python中静态方法的实现
- Python的静态方法和类成员方法
- python里关于类方法和静态方法的区别
- python类方法和静态方法
- python中的静态成员方法 和 类成员方法
- [Dynamic Language] Python 静态方法、类方法、属性
- [总结]python 静态方法与类方法
- python类方法和静态方法
- 在python种实现类的静态方法
- PYTHON中的静态方法和类方法
- python的静态方法
- python的类方法和类的静态方法
- python 静态方法和类方法
- Python 静态方法与类方法