美文网首页
Python @property 详解

Python @property 详解

作者: Double_E | 来源:发表于2017-03-29 20:36 被阅读236次
    • 类方法转为只读属性

    • 重新实现属性的setter, getter, deleter方法

    类方法转为只读属性

    class Jhy(object):
        """docstring for Jhy"""
        def __init__(self, a, b):
            self.a = a
            self.b = b
    
        def all(self):
            return ('a: {}, b: {}'.format(self.a, self.b))
        @property
        def all2(self):
            return('a: {}, b: {}'.format(self.a, self.b))
        
    
    if __name__ == '__main__':
        jhy = Jhy('name1', 'name2')
        print(jhy.all()) #方法调用有()
        print(jhy.all2) #属性调用没()
        jhy.all2 = 11 # 这个属性赋值会报错
    
    输出:
    a: name1, b: name2
    a: name1, b: name2
    jhy.all2 = 11 AttributeError: can't set attribute
    

    property代替 setter和getter, deleter方法, 类方法转为可修改属性

    class Jhy(object):
        """docstring for Jhy"""
    
    
        @property
        def all(self):
            return self._all
    
        @all.setter #  设置属性修改方法 ,这里all = property(all)
        def all(self, a):
            if a != 1:
                self._all = a 
            else:
                print('Need a != 1')
    
        @all.deleter
        def all(self):
            del self._all
            pass
    
    
    
        
    
    if __name__ == '__main__':
        jhy = Jhy()
        jhy.all = 11
        print(jhy.all) # 输出11
        del jhy.all
        print(jhy.all) # 报错 因为已经删除了
     输出:
    11
    Traceback (most recent call last):
      File "C:\Users\jhy\Desktop\Tensorflow Demo\2.py", line 36, in <module>
        print(jhy.all)
      File "C:\Users\jhy\Desktop\Tensorflow Demo\2.py", line 14, in all
        return self._all
    AttributeError: 'Jhy' object has no attribute '_all
    
    

    实例

    tensorflow/python/ops/control_flow_ops.py

    Paste_Image.png

    相关文章

      网友评论

          本文标题:Python @property 详解

          本文链接:https://www.haomeiwen.com/subject/cfyyottx.html