The Python Oracle

Python3: Class inheritance and private fields

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 2 Looping

--

Chapters
00:00 Python3: Class Inheritance And Private Fields
01:12 Accepted Answer Score 4
02:11 Thank you

--

Full question
https://stackoverflow.com/questions/4685...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #oop #inheritance

#avk47



ACCEPTED ANSWER

Score 4


Python doesn't really have private variables, there are two conventions:

  • Variables prefixed with underscore (_var) are used to let you and other people know that it's intended to be private
  • Variables prefixed with two undersores (__var) are also mangled by python interpreter and also are prefixed by class name, but they are still accessible like self._Superclass__var in your example

See also the documentation.

There is one more issue in your code - you are using class variables, not instance variables (this is what usually called static class variables in other languages).

Check this example:

class Superclass:
    var = 1

    def getVar(self):
        print(self.var)

my_object = Superclass()
my_object2 = Superclass()
my_object.getVar()  # outputs 1
my_object2.getVar()  # outputs 1

Superclass.var = 321  # this value is share across all instances
my_object.getVar()  # outputs 321
my_object2.getVar()  # outputs 321

And when you are doing self.var = xxx assignments in your methods, you just hide the class-level variable and add the new instance-level variable with same name.

See also the documentation: https://docs.python.org/3.6/tutorial/classes.html#class-and-instance-variables