
Object Oriented Programming in Python: Encapsulation and Inheritance - leandrotk
https://medium.com/the-renaissance-developer/python-101-object-oriented-programming-part-2-8e0db3ddd531
======
Walkman
There is no such thing as "private" or "public" instance variable in Python.
This guy should not teach...

~~~
Sjenk
Well it is not intergrated in the language like i.e Java or C#. But Python
does have the naming convention to mark vars that should not be touched with
__ [0]

[0] [https://docs.python.org/2/tutorial/classes.html#private-
vari...](https://docs.python.org/2/tutorial/classes.html#private-variables-
and-class-local-references)

~~~
travisjungroth
You and the article author both didn't seem to read that link.

A single leading underscore is a convention to mark a variable as private.

A double leading underscore "name mangles" the variable (adds the class to the
name of the variable) and has a specific use case for inheritance. They're
class level private, which is probably not what you want.

    
    
        class Number:
            def __init__(self, n):
                self._number = n
                self.__number = n
        
        
        class NumberChild(Number):
            def one_higher(self):
                return self._number + 1
        
            def two_higher(self):
                return self.__number + 2
        
        
        number_child = NumberChild(10)
        number_child.one_higher()  # This works
        number_child.two_higher()  # This raises an Attribute Error

~~~
geezerjay
Exactly. This is even stated quite clearly in PEP 8.

[https://www.python.org/dev/peps/pep-0008/](https://www.python.org/dev/peps/pep-0008/)

------
fermigier
Much of the code in the post could be simplified by using the awesome `attrs`
package [1].

Or if / when PEP 557 gets adopted.

[1]: [https://github.com/python-attrs/attrs](https://github.com/python-
attrs/attrs)

[2]:
[https://www.python.org/dev/peps/pep-0557/](https://www.python.org/dev/peps/pep-0557/)

~~~
smegel
That looks good. Python has long needed something like this.

