zoukankan      html  css  js  c++  java
  • 静态方法、类方法、属性方法

    静态方法:通过加@staticmethod实现,只是名义上归类管理,实际上在静态方法里访问不了类或实例中的任何属性。

    class Person(object):
        @staticmethod
        def person_speak(obj):
            print('I like Hiphop!')
    
    me = Person()
    me.person_speak(me)
    Person.person_speak(me)
    
    # I like Hiphop! 
    # I like Hiphop! 

    类方法:通过加@classmethod实现,只能访问类变量,不能访问实例变量。

    class Person(object):
        sex = 'man'
        def __init__(self, sex):
            self.sex = sex
        # @classmethod
        def hello(self):
            print('I am {}'.format(self.sex))
    
    me = Person('woman')
    me.hello()
    
    # I am woman
    # 去掉装饰器的注释后,输出
    # I am man

    属性方法:通过加@property实现,把一个方法变成静态属性

    class Person(object):
        n = 1
        @property
        def hello(self):
            print(self.n)
    
    me = Person()
    me.hello

    # 输出
    # 1

    一般的属性都可以赋值,但是属性方法的赋值特殊处理

    class Person(object):
        def __init__(self):
            self.__n = 1
        @property
        def hello(self):
            return self.__n
        @hello.setter
        def hello(self, n):
            self.__n = n
    
    
    me = Person()
    print(me.hello) # 1
    me.hello = 666
    print(me.hello) # 666

    同理,也可以删除

    class Person(object):
        def __init__(self):
            self.__n = 1
        @property
        def hello(self):
            return self.__n
        @hello.setter
        def hello(self, n):
            self.__n = n
        @hello.deleter
        def hello(self):
            del self.__n
    
    me = Person()
    me.hello = 666
    del me.hello
    me.hello
    
    Traceback (most recent call last):
      File "oop.py", line 19, in <module>
        me.hello
      File "oop.py", line 8, in hello
        return self.__n
    AttributeError: 'Person' object has no attribute '_Person__n'
  • 相关阅读:
    Hibernate 之核心接口
    [综]隐马尔可夫模型Hidden Markov Model (HMM)
    [zz]利用碎片时间健身
    [zz]简单有效,在家就能锻炼!
    matlab global 不能传向量/矩阵
    [zz] 基于国家标准的 EndNote 输出样式模板
    [zz] ROC曲线
    [ZZ] Equal Error Rate (EER)
    [综] Sparse Representation 稀疏表示 压缩感知
    [zz] Principal Components Analysis (PCA) 主成分分析
  • 原文地址:https://www.cnblogs.com/allenzhang-920/p/9393357.html
Copyright © 2011-2022 走看看