Python @property 详解

2017-03-29  本文已影响236人  Double_E

类方法转为只读属性

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
上一篇下一篇

猜你喜欢

热点阅读