我应该使用属性还是getter和setter方法? [英] Should I use properties or getters and setters?

查看:94
本文介绍了我应该使用属性还是getter和setter方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在python中使用getter和setters不是pythonic.应该使用属性装饰器.但我想知道以下情况-

I know that it is not pythonic to use getters and setters in python. Rather property decorators should be used. But I am wondering about the following scenario -

我有一个用一些实例属性初始化的类.然后,稍后我需要向该类添加其他实例属性.如果我不使用设置器,则必须在类外的任何地方编写object.attribute = value.该类将没有self.attribute代码.当我需要跟踪类的属性时(因为它们散布在类外部的代码中),这是否会成为问题?

I have a class initialized with a few instance attributes. Then later on I need to add other instance attributes to the class. If I don't use setters, then I have to write object.attribute = value everywhere outside the class. The class will not have the self.attribute code. Won't this become a problem when I need to track the attributes of the class (because they are strewn all over the code outside the class)?

推荐答案

通常,您甚至都不应该使用属性.简单的属性在大多数情况下都可以正常工作:

In general, you shouldn't even use properties. Simple attributes work just fine in the vast majority of cases:

class X:
    pass

>>> x = X()
>>> x.a
Traceback (most recent call last):
  # ... etc
AttributeError: 'X' object has no attribute 'a'
>>> x.a = 'foo'
>>> x.a
'foo'

只有在访问属性时需要 做一些工作的情况下,才应使用属性:

A property should only be used if you need to do some work when accessing an attribute:

import random

class X:

    @property
    def a(self):
        return random.random()

>>> x = X()
>>> x.a
0.8467160913203089

如果还需要能够分配给属性,则定义一个setter很简单:

If you also need to be able to assign to a property, defining a setter is straightforward:

class X:

    @property
    def a(self):
        # do something clever
        return self._a

    @a.setter
    def a(self, value):
        # do something even cleverer
        self._a = value

>>> x = X()
>>> x.a
Traceback (most recent call last):
  # ... etc
AttributeError: 'X' object has no attribute '_a'
>>> x.a = 'foo'
>>> x.a
'foo'

请注意,在每种情况下,客户端代码访问属性或属性的方式都是完全相同的.无需为类提供面向未来的"功能,以免在某些时候您可能想做一些比简单属性访问更复杂的事情,因此,除非您确实需要正确的属性,getter或setters,否则没有理由编写它们现在.

Notice that in each case, the way that client code accesses the attribute or property is exactly the same. There's no need to "future-proof" your class against the possibility that at some point you might want to do something more complex than simple attribute access, so no reason to write properties, getters or setters unless you actually need them right now.

有关特性,getter和setter方面的惯用Python与其他语言之间的区别的更多信息,请参见:

For more on the differences between idiomatic Python and some other languages when it comes to properties, getters and setters, see:

  • Why don't you want getters and setters?
  • Python is not Java (especially the "Getters and setters are evil" section)

这篇关于我应该使用属性还是getter和setter方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆