时间:2010-07-26 16:19:25

标签: python properties

2 个答案:

答案 0 :(得分:28)

要覆盖python 2中的setter,我这样做了:

class A(object):
    def __init__(self):
        self._attr = None

    @property
    def attr(self):
        return self._attr

    @attr.setter
    def attr(self, value):
        self._attr = value


class B(A):
    @A.attr.setter
    def attr(self, value):
        # Do some crazy stuff with `value`
        value = value[0:3]
        A.attr.fset(self, value)

要了解A.attr.fset的来源,请参阅property类的文档: https://docs.python.org/2/library/functions.html#property

答案 1 :(得分:5)