Section 97.1: 为读写属性使用 @property 装饰器

如果要使用 @property 实现自定义设置和获取行为,请使用此模式:

class Cash(object):
  def __init__(self, value):
    self.value = value

  @property
  def formatted(self):
    return '${:.2f}'.format(self.value)

  @formatted.setter
  def formatted(self, new):
    self.value = float(new[1:])

使用方法

>>> wallet = Cash(2.50)
>>> print(wallet.formatted)
$2.50
>>> print(wallet.value)
2.5
>>> wallet.formatted = '$123.45'
>>> print(wallet.formatted)
$123.45
>>> print(wallet.value)
123.45

为读写属性使用 @property 装饰器

Section 97.2: 使用 @property 装饰器

@property 装饰器可用于在类中定义类似属性的方法。其中一个有用的例子是,在公开信息时,可能需要进行初始(昂贵的)查询,然后再进行简单的检索。

给定模块 foobar.py:

class Foo(object):
  def __init__(self):
    self.__bar = None

  @property
  def bar(self):
    if self.__bar is None:
      self.__bar = some_expensive_lookup_operation()
    return self.__bar

  def some_expensive_lookup_operation(self):
    # 模拟耗时操作,例如从数据库或网络获取数据
    import time
    time.sleep(2)  # 模拟耗时
    return 42

那么

>>> from foobar import Foo
>>> foo = Foo()
>>> print(foo.bar) # 这将需要一些时间,因为bar在初始化后为None
42
>>> print(foo.bar) # 这要快得多,因为bar现在有值了
42

Section 97.3: 仅重写属性对象的获取器、设置器或删除器

从带有属性的类继承时,可以通过引用父类上的属性对象,为一个或多个属性的获取、设置或删除函数提供新的实现:

class BaseClass(object):
  @property
  def foo(self):
    return some_calculated_value()

  @foo.setter
  def foo(self, value):
    do_something_with_value(value)

class DerivedClass(BaseClass):
  @BaseClass.foo.setter
  def foo(self, value):
    do_something_different_with_value(value)

您还可以在基类中没有设置的地方添加设置器或删除器。

Section 97.4: 使用不带装饰器的属性

虽然使用装饰器语法(带 @)很方便,但也有点遮遮掩掩。您可以直接使用属性,而不使用装饰器。下面的 Python 3.x 示例说明了这一点:

class A:
  p = 1234
  def getX (self):
    return self._x

  def setX (self, value):
    self._x = value

  def getY (self):
    return self._y

  def setY (self, value):
    self._y = 1000 + value # Weird but possible

  def getY2 (self):
    return self._y

  def setY2 (self, value):
    self._y = value

  def getT (self):
    return self._t

  def setT (self, value):
    self._t = value

  def getU (self):
    return self._u + 10000

  def setU (self, value):
    self._u = value - 5000
    x, y, y2 = property (getX, setX), property (getY, setY), property (getY2, setY2)
    t = property (getT, setT)
    u = property (getU, setU)

A.q = 5678

class B:
  def getZ (self):
    return self.z_

  def setZ (self, value):
    self.z_ = value

  z = property (getZ, setZ)

class C:
  def __init__ (self):
    self.offset = 1234

  def getW (self):
    return self.w_ + self.offset

  def setW (self, value):
    self.w_ = value - self.offset

  w = property (getW, setW)

a1 = A ()
a2 = A ()

a1.y2 = 1000
a2.y2 = 2000

a1.x = 5
a1.y = 6

a2.x = 7
a2.y = 8

a1.t = 77
a1.u = 88

print (a1.x, a1.y, a1.y2)
print (a2.x, a2.y, a2.y2)
print (a1.p, a2.p, a1.q, a2.q)

print (a1.t, a1.u)

b = B ()
c = C ()

b.z = 100100
c.z = 200200
c.w = 300300

print (a1.x, b.z, c.z, c.w)

c.w = 400400
c.z = 500500
b.z = 600600

print (a1.x, b.z, c.z, c.w)

使用不带装饰器的属性

使用不带装饰器的属性

使用不带装饰器的属性