Python Property类

学习openpyxl 操作Excel时:

sheet_names = wb.get_sheet_names() 提示: DeprecationWarning: Call to deprecated function get_sheet_names (Use wb.sheetnames).

函数废弃,请使用对象点的方式,于是看了源码,才发现装饰器修饰函数返回属性值

  • 对象.属性触发getter
  • 对象.属性 = 属性值 触发setter
  • del 对象.属性 触发deleter

官方文档:

 """
    Property attribute.
    
      fget
        function to be used for getting an attribute value
      fset
        function to be used for setting an attribute value
      fdel
        function to be used for del'ing an attribute
      doc
        docstring
    
    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 A(object):
    def __init__(self):
        self._age = 18

    @property
    def age(self):
        print('getter run ...')
        return self._age

    @age.setter
    def age(self, age):
        print('seter run...')
        self._age = age

    @age.deleter
    def age(self):
        print('del run ...')
        del self._age

输出:

getter run ...
18
seter run...
getter run ...
18
del run ...

Process finished with exit code 0
posted @ 2022-01-11 16:07  chuangzhou  阅读(197)  评论(0编辑  收藏  举报