"public" or "private" attribute in Python ? What is the best way ?

Posted by SeyZ on Stack Overflow See other posts from Stack Overflow or by SeyZ
Published on 2010-12-29T16:41:39Z Indexed on 2010/12/29 16:54 UTC
Read the original article Hit count: 149

Filed under:
|
|
|

Hi !

In Python, I have the following example class :

class Foo:
    self._attr = 0

    @property
    def attr(self):
        return self._attr

    @attr.setter
    def attr(self, value):
        self._attr = value

    @attr.deleter
    def attr(self):
        del self._attr

As you can see, I have a simple "private" attribute "_attr" and a property to access it. There is a lot of codes to declare a simple private attribute and I think that it's not respecting the "KISS" philosophy to declare all attributes like that.

So, why not declare all my attributes as public attributes if I don't need a particular getter/setter/deleter ?

My answer will be : Because the principle of encapsulation (OOP) says otherwise!

What is the best way ?

Thanks !

© Stack Overflow or respective owner

Related posts about python

Related posts about oop