3

由于 Python 力求找到一种正确的方法,我想知道 property.getter 的目的是什么。在此示例中,WhyMe 定义了一个 getter,但 Other 没有,所以我想知道 property.getter 仅使用属性的意义何在。

class WhyMe(object):
    def __init__(self):
        self._val = 44

    @property
    def val(self):
        print 'I am not called'
        return self._val

    @val.getter # What advantage do I bring?
    def val(self):
        print 'getter called'
        return self._val

class Other(object):
    def __init__(self):
        self._val = 44

    @property
    def val(self):
        print 'I AM called'
        return self._val

并使用它们:

>>> why = WhyMe()
>>> why.val
getter called
44
>>> other = Other()
>>> other.val
I AM called
44

我对属性并不陌生,我只是想知道制作吸气剂是否有一些优势,或者是否只是为了对称而放在那里?

4

1 回答 1

5

@property让我们通过为该属性定义一个 getter 来定义一个全新的属性。该@original.getter语法允许您仅覆盖现有的 getter。对于属性可用的其他两种方法,还有装饰.setter器。.deleter

想象一下,您对使用属性的自定义类进行子类化,同时定义了 getter 和 setter。如果您只想覆盖该属性的getter,但将setter(或删除器)留在原处,则 using@BaseClass.original.getter允许您这样做:

>>> class Foo(object):
...     @property
...     def spam(self):
...         print 'Foo.spam called'
...         return 'spam'
...     @spam.setter
...     def spam(self, value):
...         print 'Foo.spam.setter called'
...     @property
...     def ham(self):
...         print 'Foo.ham called'
...         return 'ham'
...     @ham.setter
...     def ham(self, value):
...         print 'Foo.ham.setter called'
... 
>>> class Bar(Foo):
...     @Foo.spam.getter
...     def spam(self):
...         print 'Bar.spam override'
...         return 'eggs and spam'
...     @property
...     def ham(self):
...         print 'Bar.ham override'
...         return 'eggs and ham'
... 
>>> Bar().spam
Bar.spam override
'eggs and spam'
>>> Bar().spam = 'foo'
Foo.spam.setter called
>>> Bar().ham
Bar.ham override
'eggs and ham'
>>> Bar().ham = 'foo'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

请注意,我只替换了spam getter,而它的 setter 被保留了。Bar.hamsetter不存在,我更换了物业Foo.ham批发。

于 2013-01-03T12:05:23.543 回答