欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Python 学习入门(37)—— @classmethod函数

程序员文章站 2022-09-14 20:14:58
@classmethod : 类方法@staticmethod : 静态方法类方法和静态方法的调用一样,都是通过类就可以直接调用。区别:类方法,需要传入该类,定义类方法的时候要传一...

@classmethod : 类方法

@staticmethod : 静态方法

类方法和静态方法的调用一样,都是通过类就可以直接调用。

区别:类方法,需要传入该类,定义类方法的时候要传一个默认的参数cls。静态方法则不用。


示例:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# blog.ithomer.net

class test(object):
    x = 11
    def __init__(self, _x):
        self._x = _x
        print("test.__init__")
 
    @classmethod
    def class_method(cls):
        print("class_method")
 
    @staticmethod
    def static_method():
        print("static_method")
 
    @classmethod
    def getpt(cls):
        cls.class_method()
        cls.static_method()
 
if "__main__" == __name__:
    test.class_method()         # class_method
    test.static_method()        # static_method
    test.getpt()                # class_method  static_method

    t = test(22)                # test.__init__
    t.class_method()            # class_method
    t.static_method()           # static_method
    
    print test.x                # 11
#     print test._x
    
    print t.x                   # 11
    print 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 
    t.getpr() 
attributeerror: 'test' object has no attribute 'getpr'

示例:@property,@staticmethod,@classmethod

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# blog.ithomer.net

class myclass(object):
    def __init__(self):
        print '__init__'
        self._name = 'blog.ithomer.net'

    @staticmethod
    def static_method():
        print 'this is a static method!'

    def test(self):
        print 'call test'

    @classmethod
    def class_method(cls):
        print 'cls: ',cls
        print 'cls.name: ',cls.name
        print 'cls.static_method(): ',cls.static_method()
        instance = cls()
        print 'instance.test(): ',instance.test()

    @property
    def name(self):
        return self._name
    
    @name.setter
    def name(self, value):
        self._name = value

if __name__ == '__main__':
    myclass.static_method()
    myclass.class_method()
    
    mc = myclass()
    print mc.name
    mc.name = 'forum.ithomer.net'  
    print mc.name
运行结果:

this is a static method!
cls:
cls.name:
cls.static_method(): this is a static method!
none
__init__
instance.test(): call test
none
__init__
blog.ithomer.net
forum.ithomer.net