Should I use properties or getters and setters?

泄露秘密 提交于 2020-07-03 03:04:44

问题


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 -

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)?


回答1:


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

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'

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.

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)


来源:https://stackoverflow.com/questions/43896134/should-i-use-properties-or-getters-and-setters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!