Should I use properties or getters and setters?

后端 未结 1 579
小蘑菇
小蘑菇 2021-01-12 21:18

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 h

1条回答
  •  一生所求
    2021-01-12 21:35

    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)

    0 讨论(0)
提交回复
热议问题