python property/getter/setter/deleter/_/__

描述: property/getter/setter/deleter, _, __
property: read only
setter: read and write
getter: read
deleter: delete
属性特征:
public: 无标记
protected: _ (单下划线)
【python property/getter/setter/deleter/_/__】private: __ (双下划线)

# -*- coding: utf8 -*-class First(object):def __init__(self): self._name = 'init_name' self.__age = 18@property def name(self): return self._name@name.getter def name(self): return self._name@name.setter def name(self, value): self._name = value@name.deleter def name(self): del self._nameif __name__ == '__main__': a = First() print(a.name) a.name = 'hello' print(a.name) try: del a.name print(a.name) except Exception as ex: print("exception:", ex) a.name = 'world' print(a.name) print("* *" * 30) print(dir(a)) print(a._name) print(a._First__age)


输出:
init_name
hello
exception: 'First' object has no attribute '_name'
world
* ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** *
['_First__age', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_name', 'name']
world
18



    推荐阅读