与经典的getter+setter相比,@property表示法有什么优点?在哪些特定的情况下,程序员应该选择使用其中一种而不是另一种?

属性:

class MyClass(object):
    @property
    def my_attr(self):
        return self._my_attr

    @my_attr.setter
    def my_attr(self, value):
        self._my_attr = value

没有属性:

class MyClass(object):
    def get_my_attr(self):
        return self._my_attr

    def set_my_attr(self, value):
        self._my_attr = value

当前回答

以下是摘自《有效的Python: 90种具体方法来编写更好的Python》(一本令人惊叹的书)的节选。我强烈推荐)。

Things to Remember ✦ Define new class interfaces using simple public attributes and avoid defining setter and getter methods. ✦ Use @property to define special behavior when attributes are accessed on your objects, if necessary. ✦ Follow the rule of least surprise and avoid odd side effects in your @property methods. ✦ Ensure that @property methods are fast; for slow or complex work—especially involving I/O or causing side effects—use normal methods instead. One advanced but common use of @property is transitioning what was once a simple numerical attribute into an on-the-fly calculation. This is extremely helpful because it lets you migrate all existing usage of a class to have new behaviors without requiring any of the call sites to be rewritten (which is especially important if there’s calling code that you don’t control). @property also provides an important stopgap for improving interfaces over time. I especially like @property because it lets you make incremental progress toward a better data model over time. @property is a tool to help you address problems you’ll come across in real-world code. Don’t overuse it. When you find yourself repeatedly extending @property methods, it’s probably time to refactor your class instead of further paving over your code’s poor design. ✦ Use @property to give existing instance attributes new functionality. ✦ Make incremental progress toward better data models by using @property. ✦ Consider refactoring a class and all call sites when you find yourself using @property too heavily.

其他回答

以下是摘自《有效的Python: 90种具体方法来编写更好的Python》(一本令人惊叹的书)的节选。我强烈推荐)。

Things to Remember ✦ Define new class interfaces using simple public attributes and avoid defining setter and getter methods. ✦ Use @property to define special behavior when attributes are accessed on your objects, if necessary. ✦ Follow the rule of least surprise and avoid odd side effects in your @property methods. ✦ Ensure that @property methods are fast; for slow or complex work—especially involving I/O or causing side effects—use normal methods instead. One advanced but common use of @property is transitioning what was once a simple numerical attribute into an on-the-fly calculation. This is extremely helpful because it lets you migrate all existing usage of a class to have new behaviors without requiring any of the call sites to be rewritten (which is especially important if there’s calling code that you don’t control). @property also provides an important stopgap for improving interfaces over time. I especially like @property because it lets you make incremental progress toward a better data model over time. @property is a tool to help you address problems you’ll come across in real-world code. Don’t overuse it. When you find yourself repeatedly extending @property methods, it’s probably time to refactor your class instead of further paving over your code’s poor design. ✦ Use @property to give existing instance attributes new functionality. ✦ Make incremental progress toward better data models by using @property. ✦ Consider refactoring a class and all call sites when you find yourself using @property too heavily.

喜欢的属性。这就是他们存在的意义。

原因是Python中的所有属性都是公共的。以下划线或两个下划线开头的名称只是一个警告,说明给定的属性是一个实现细节,在将来的代码版本中可能不会保持相同。它不会阻止您实际获取或设置该属性。因此,标准属性访问是访问属性的正常的python方式。

属性的优点是它们在语法上与属性访问相同,因此您可以在不更改客户机代码的情况下从一个属性更改到另一个属性。您甚至可以有一个版本的类使用属性(例如,用于契约代码或调试),而另一个版本的类不用于生产,而不需要更改使用它的代码。与此同时,您不必为所有内容编写getter和setter,以防以后可能需要更好地控制访问。

简单的答案是:properties轻松获胜。总是这样。

有时需要getter和setter,但即使这样,我也会将它们“隐藏”到外部世界。在Python中有很多方法可以做到这一点(getattr, setattr, __getattribute__,等等…,但最简洁明了的是:

def set_email(self, value):
    if '@' not in value:
        raise Exception("This doesn't look like an email address.")
    self._email = value

def get_email(self):
    return self._email

email = property(get_email, set_email)

下面是一篇简短的文章,介绍Python中的getter和setter主题。

在大多数情况下,我宁愿两者都不使用。属性的问题是它们使类不那么透明。特别是,如果要从setter引发异常,这是一个问题。例如,如果您有一个帐户。电子邮件属性:

class Account(object):
    @property
    def email(self):
        return self._email

    @email.setter
    def email(self, value):
        if '@' not in value:
            raise ValueError('Invalid email address.')
        self._email = value

这样,类的用户就不会期望给属性赋值会导致异常:

a = Account()
a.email = 'badaddress'
--> ValueError: Invalid email address.

结果,异常可能得不到处理,或者在调用链中传播得太高而无法正确处理,或者导致向程序用户提供非常无用的回溯(遗憾的是,这在python和java世界中太常见了)。

我也会避免使用getter和setter:

因为提前为所有属性定义它们非常耗时, 使代码的数量不必要地变长,这使得理解和维护代码更加困难, 如果只在需要时为属性定义它们,类的接口将会改变,损害类的所有用户

而不是属性和getter /setter,我更喜欢在定义良好的地方执行复杂的逻辑,例如在验证方法中:

class Account(object):
    ...
    def validate(self):
        if '@' not in self.email:
            raise ValueError('Invalid email address.')

或类似帐户。保存方法。

请注意,我并不是想说在任何情况下属性都是有用的,只是说如果您可以使您的类足够简单和透明,以至于您不需要它们,那么您可能会更好。

我觉得属性是为了让您在真正需要getter和setter时才编写它们。

Java编程文化强烈建议永远不要授予对属性的访问权,相反,只访问实际需要的getter和setter。 总是编写这些显而易见的代码段有点啰嗦,请注意,70%的情况下,它们从未被一些重要的逻辑所取代。

在Python中,人们实际上关心这种开销,因此您可以采用以下实践:

不使用getter和setter在第一次,如果他们不需要 使用@property来实现它们,而不改变其余代码的语法。