Python ---- 属性装饰器

property源码帮助

"""
Typical use is to define a managed attribute x:
        
        class C(object):
            def getx(self): return self._x
            def setx(self, value): self._x = value
            def delx(self): del self._x
            x = property(getx, setx, delx, "I'm the 'x' property.")
        
        Decorators make defining new properties or modifying existing ones easy:
        
        class C(object):
            @property
            def x(self):
                "I am the 'x' property."
                return self._x
            @x.setter
            def x(self, value):
                self._x = value
            @x.deleter
            def x(self):
                del self._x
"""
class Person:
    def __init__(self, chinese, english, history):
        self._chinese = chinese
        self._eng = english
        self.__his = history

    def getscore(self):
        return (self._chinese, self._eng, self.__his)

    def gethis(self): # getter 可读
        return self.__his

    def sethis(self, value): # setter 可写
        self.__his = value

    def geteng(self):  # 只读属性
        return self._eng

    @property # 将下面方法变成类型属性那样可以直接访问他,根据property源码中帮助着写
    def chinese(self):
        return self._chinese
    
    @chinese.setter # 将下面方法中的属性进行修改
    def chinese(self,value):
        self._chinese = value
    
    @chinese.deleter
    def chinese(self):
        #del self._chinese
        print('del chinese')

student1 = Person(80, 90, 88)
# print(student1.gethis())
print(student1.chinese)
# 将方法当做属性应用
student1.chinese = 100 
print(student1.chinese)
del student1.chinese

#+++++++++++++++++++++++++优雅
class Person:
    def __init__(self, chinese, english, history):
        self._chinese = chinese
        self._eng = english
        self.__his = history

    def getscore(self):
        return (self._chinese, self._eng, self.__his)

    def gethis(self): # getter 可读
        return self.__his

    def sethis(self, value): # setter 可写
        self.__his = value

    def geteng(self):  # 只读属性
        return self._eng

    @property # 将下面方法变成类型属性那样可以直接访问他,根据property源码中帮助着写
    def chinese(self):
        return self._chinese
    
    @chinese.setter # 将下面方法中的属性进行修改
    def chinese(self,value):
        self._chinese = value
    
    @chinese.deleter
    def chinese(self):
        #del self._chinese
        print('del chinese')

    eng = property(lambda self:self._eng, seteng)
    
student1 = Person(80, 90, 88)
# print(student1.gethis())
print(student1.chinese)
# 将方法当做属性应用
student1.chinese = 100 
print(student1.chinese)
print(student1.eng)
student1._eng = 200
print(student1.eng)
posted @ 2021-03-02 15:29  k-free  阅读(152)  评论(0编辑  收藏  举报