property

阅读量: 鲁文奎 2021-04-22 12:04:47
Categories: Tags:

property

[toc]

前言

属性 是python中保护字段的一种手段。主要有以下应用场景:

基本用法

以下2中关于属性的用法基本没啥区别, 以下2个例子均来自于官方文档。

一般用法

class C(object):
    def __init__(self):
        self._x = None

    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.")

装饰器用法

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

源码探究

class Foo(object):
    pass
foo = Foo()
foo.a = 10
Foo.b = property(lambda self: self.a + 1)

# 输出
f
  1. 在调用此属性的实例的class中查找此字段, 如果找到了, 则调用property中的property_descr_get函数 ---> 调用get函数
  2. 如果没有找到, 查找实例对象中__dict__中的所有key, 如果找到了, 直接返回该字段
  3. 如果又没有找到, 则没有该字段