python class的只读属性设置

只读属性的设置

 


class Person:
def __init__(self):
self.__age=30
self.__name="default"
#这里是方法1
@property
def age(self):
return self.__age
@age.setter
def age(self,value):
self.__age=20
@age.deleter
def age(self):
del self.__age
#这里是方法2
    def get_name(self):
return self.__name

def set_name(self, value):
self.__name = value
    def del_name(self):
del self.__age
    name=property(get_name,set_name,del_name)

p1=Person()
print(p1.age)
p1.age=10
print(p1.age)
print(p1.name)
p1.name="world"
print(p1.name)
print(p1.__dict__)
print(Person.__dict__)
print(Person.__base__)
print(Person.__doc__)
print(Person.__name__)
print(Person.__module__)
print(p1.__class__)

30
20
default
world
{'_Person__age': 20, '_Person__name': 'world'}
{'__module__': '__main__', '__init__': <function Person.__init__ at 0x0000020B30CD6EE8>, 'age': <property object at 0x0000020B2EDB5E08>, 'get_name': <function Person.get_name at 0x0000020B30CE3A68>, 'set_name': <function Person.set_name at 0x0000020B30CE39D8>, 'name': <property object at 0x0000020B30CF3818>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}
<class 'object'>
None
Person
__main__
<class '__main__.Person'>

posted on 2020-01-08 07:41  InnoLeo  阅读(787)  评论(0编辑  收藏  举报