本文主要是介绍Python 学习入门(37)—— @classmethod函数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
@classmethod : 类方法
@staticmethod : 静态方法
类方法和静态方法的调用一样,都是通过类就可以直接调用。
区别:类方法,需要传入该类,定义类方法的时候要传一个默认的参数cls。静态方法则不用。
示例:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# blog.ithomer.netclass Test(object):x = 11def __init__(self, _x):self._x = _xprint("Test.__init__")@classmethoddef class_method(cls):print("class_method")@staticmethoddef static_method():print("static_method")@classmethoddef getPt(cls):cls.class_method()cls.static_method()if "__main__" == __name__:Test.class_method() # class_methodTest.static_method() # static_methodTest.getPt() # class_method static_methodt = Test(22) # Test.__init__t.class_method() # class_methodt.static_method() # static_methodprint Test.x # 11
# print Test._xprint t.x # 11print t._x # 22# t.getPr() # 'Test' object has no attribute 'getPr'
运行结果:
class_method
static_method
class_method
static_method
Test.__init__
class_method
static_method
11
11
22
Traceback (most recent call last):File "/home/homer/workspace/myPython/com/connmiliao.py", line 40, in <module>t.getPr()
AttributeError: 'Test' object has no attribute 'getPr'
示例:@property,@staticmethod,@classmethod
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# blog.ithomer.netclass MyClass(object):def __init__(self):print '__init__'self._name = 'blog.ithomer.net'@staticmethoddef static_method():print 'This is a static method!'def test(self):print 'call test'@classmethoddef class_method(cls):print 'cls: ',clsprint 'cls.name: ',cls.nameprint 'cls.static_method(): ',cls.static_method()instance = cls()print 'instance.test(): ',instance.test()@propertydef name(self):return self._name@name.setterdef name(self, value):self._name = valueif __name__ == '__main__':MyClass.static_method()MyClass.class_method()mc = MyClass()print mc.namemc.name = 'forum.ithomer.net' print mc.name
运行结果:
This is a static method!
cls: <class '__main__.MyClass'>
cls.name: <property object at 0x150d680>
cls.static_method(): This is a static method!
None
__init__
instance.test(): call test
None
__init__
blog.ithomer.net
forum.ithomer.net
这篇关于Python 学习入门(37)—— @classmethod函数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!