【问题标题】:What is the purpose of Python's property.getter?Python的property.getter的目的是什么?
【发布时间】:2012-12-17 19:06:06
【问题描述】:

既然 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

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

【问题讨论】:

    标签: python new-style-class


    【解决方案1】:

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

    想象一下,您将使用属性的自定义类子类化,同时定义了 getter 和 setter。如果您只想覆盖该属性的 getter 而将 setter 留在原处(或删除器),则使用 @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.ham setter 不存在,我替换了 Foo.ham 属性批发。

    【讨论】:

    • 谢谢,这正是我想要的。我很惊讶地意识到,在我使用 python 的这些年里,我从来不需要覆盖子类中的属性。
    猜你喜欢
    • 2021-05-27
    • 1970-01-01
    • 2021-12-22
    • 2017-05-04
    • 2012-02-21
    • 2010-10-17
    • 2021-08-09
    • 2016-06-30
    相关资源
    最近更新 更多