python classmethod类方法
2015-04-29 15:09
323 查看
python classmethod类方法的要点主要有3个:
1 在python中.类方法 @classmethod 是一个函数修饰符,它表示接下来的是一个类方法,而对于平常我们见到的则叫做实例方法。 类方法的第一个参数cls,而实例方法的第一个参数是self,表示该类的一个实例。
2 普通对象方法至少需要一个self参数,代表类对象实例
3
类方法有类变量cls传入,从而可以用cls做一些相关的处理。并且有子类继承时,调用该类方法时,传入的类变量cls是子类,而非父类。 对于类方法,可以通过类来调用,就像C.f(),有点类似C++中的静态方法, 也可以通过类的一个实例来调用,就像C().f(),这里C(),写成这样之后它就是类的一个实例了。
class info(object):
@classmethod
def sayclassmethod(cls):
print 'say %s' % cls
def saymethod(self):
print 'say %s' % self
test
= info()
test.saymethod()##实例调用方法
test.sayclassmethod()##实例调用类方法
info.saymethod(test)##类调用实例方法
info.sayclassmethod()##类调用类方法
>>>
say <__main__.info object at 0x0000000002CF6278>
say <class '__main__.info'>
say <__main__.info object at 0x0000000002CF6278>
say <class '__main__.info'>
1 在python中.类方法 @classmethod 是一个函数修饰符,它表示接下来的是一个类方法,而对于平常我们见到的则叫做实例方法。 类方法的第一个参数cls,而实例方法的第一个参数是self,表示该类的一个实例。
2 普通对象方法至少需要一个self参数,代表类对象实例
3
类方法有类变量cls传入,从而可以用cls做一些相关的处理。并且有子类继承时,调用该类方法时,传入的类变量cls是子类,而非父类。 对于类方法,可以通过类来调用,就像C.f(),有点类似C++中的静态方法, 也可以通过类的一个实例来调用,就像C().f(),这里C(),写成这样之后它就是类的一个实例了。
class info(object):
@classmethod
def sayclassmethod(cls):
print 'say %s' % cls
def saymethod(self):
print 'say %s' % self
test
= info()
test.saymethod()##实例调用方法
test.sayclassmethod()##实例调用类方法
info.saymethod(test)##类调用实例方法
info.sayclassmethod()##类调用类方法
>>>
say <__main__.info object at 0x0000000002CF6278>
say <class '__main__.info'>
say <__main__.info object at 0x0000000002CF6278>
say <class '__main__.info'>
相关文章推荐
- 【python】详解类class的方法解析顺序MRO(Method Resolution Order)(六)
- Python 实例方法、@staticmethod和@classmethod
- python staticmethod and classmethod方法
- python 详解类class的方法解析顺序MRO(Method Resolution Order)(六)
- 转 Python 实例方法、@staticmethod和@classmethod
- Python 实例方法、@staticmethod和@classmethod
- 记录一个 关于 python 普通方法,静态方法和类方法 的介绍。@classmethod @staticmethod
- python调用py方法,报错【ValueError: no such test method in <class 'mytestcase.MyTestCase'>: runTest】
- python @classmethod 和 @staticmethod区别,以及类中方法参数cls和self的区别
- Python 实例方法、@staticmethod和@classmethod
- undefined method `devise' for User(Table doesn't exist):Class解决方法
- java.lang.Class.getDeclaredMethod()方法
- Java.lang.Class.getDeclaredMethod()方法用法
- [zz stackoverflow]Python中@staticmethod与@classme...
- 】Python @classmethod @staticmethod
- chapter9: python 类的方法,属性,迭代器(new[old]-type class,[un]bound method,super,protocol,property,iterators)
- Python: classmethod & staticmethod 区别
- 【python】classmethod & staticmethod 区别
- python MethodType方法详解和使用--转载--有删改
- Python内置函数的staticmethod()与classmethod(),@staticmethod,@classmethod