zoukankan      html  css  js  c++  java
  • Python的类实例方法,类方法,类静态方法

    以下面的类定义为例:

    # coding:utf-8
    
    class A:
        count = 0
        def __init__(self, inst_name):
            self.inst_name = inst_name
            self.__class__.count += 1
        def inst_method(self):
            print '实例(%s):%s' % (self.__class__.count, self.inst_name)
        @classmethod
        def class_method(cls):
            print cls.count
        @staticmethod
        def static_method():
            print 'hello'
    a1,a2,a3,a4 = A('a1'),A('a2'),A('a3'),A('a4')
    a1.inst_method()
    a1.class_method() # 或 A.class_method()
    a1.static_method() # 或 A.static_method()
    

    类实例方法:第一个参数强制为类实例对象,可以通过这个类实例对象访问类属性,可以通过类实例对象的__class__属性访问类属性。

    def inst_method(self):
        print '实例(%s):%s' % (self.__class__.count, self.inst_name)
    

    类实例方法不需要标注,第一个参数必不可少,解析器自动会将类实例对象传给方法的第一个参数。

    类的初始化方法__init__也是实例方法,在实例创建的时候自动调用。在这里每当初始化一个实例,就通过__class__来访问类属性count,是它加一,用来统计类的实例数。

    def __init__(self, inst_name):
        self.inst_name = inst_name
        self.__class__.count += 1
    

    类方法:第一个参数强制为类对象,可以通过这个类对象访问类属性,由于没有传入类实例对象,所以不能访问类实例属性。

    @classmethod
    def class_method(cls):
        print cls.count
    

    类方法需要使用classmethod标注,第一个参数必不可少,解析器自动会将类对象传给方法的第一个参数。

    类静态方法:无法访问类属性、类实例属性、没有默认的第一个参数,其实跟类没什么关系,只是绑定在类命名空间下的函数而已。

    @staticmethod
    def static_method():
        print 'hello'
    

    类静态方法通常用来定义一些和类主题相关的函数。

    通过类对象可以调用类方法、类静态方法,但不可以调用类实例方法;通过类实例对象可以调用以上三种方法

    a1,a2,a3,a4 = A('a1'),A('a2'),A('a3'),A('a4')
    a1.inst_method()
    a1.class_method() # 或 A.class_method()
    a1.static_method() # 或 A.static_method()
    
  • 相关阅读:
    [置顶] 内外网同时访问,我的拿来主义
    Nginx防攻击工具教程一 ngx_http_limit_conn_module
    晒晒我的厨艺修炼成果
    在 javascript 中,为什么 [1,2] + [3,4] 不等于 [1,2,3,4]?
    无法解析的外部符号__imp__AlphaBlend@44的解决
    Win32 API实现CDC类的FillSolidRect接口
    pugixml库学习之添加节点
    cleanup failed because the file not under version control问题的解决
    JavaScript 的 typeof 的用途
    支持在Win7和XP系统上创建环境变量的批处理文件
  • 原文地址:https://www.cnblogs.com/skeeter/p/3545250.html
Copyright © 2011-2022 走看看