Inheritance of private and protected methods in Python

python private method
modifier function in python
python inheritance private variables
python private variables
inheritance in python
how to define public function in python
python pseudo private
python static method

I know, there are no 'real' private/protected methods in Python. This approach isn't meant to hide anything; I just want to understand what Python does.

class Parent(object):
    def _protected(self):

    def __private(self):

class Child(Parent):
    def foo(self):
        self._protected()   # This works

    def bar(self):
        self.__private()    # This doesn't work, I get a AttributeError:
                            # 'Child' object has no attribute '_Child__private'

So, does this behaviour mean, that 'protected' methods will be inherited but 'private' won't at all? Or did I miss anything?

Python has no privacy model, there are no access modifiers like in C++, C# or Java. There are no truly 'protected' or 'private' attributes.

Names with a leading double underscore and no trailing double underscore are mangled to protect them from clashes when inherited. Subclasses can define their own __private() method and these will not interfere with the same name on the parent class. Such names are considered class private; they are still accessible from outside the class but are far less likely to accidentally clash.

Mangling is done by prepending any such name with an extra underscore and the class name (regardless of how the name is used or if it exists), effectively giving them a namespace. In the Parent class, any __private identifier is replaced (at compilation time) by the name _Parent__private, while in the Child class the identifier is replaced by _Child__private, everywhere in the class definition.

The following will work:

class Child(Parent):
    def foo(self):

    def bar(self):

See Reserved classes of identifiers in the lexical analysis documentation:

__* Class-private names. Names in this category, when used within the context of a class definition, are re-written to use a mangled form to help avoid name clashes between "private" attributes of base and derived classes.

and the referenced documentation on names:

Private name mangling: When an identifier that textually occurs in a class definition begins with two or more underscore characters and does not end in two or more underscores, it is considered a private name of that class. Private names are transformed to a longer form before code is generated for them. The transformation inserts the class name, with leading underscores removed and a single underscore inserted, in front of the name. For example, the identifier __spam occurring in a class named Ham will be transformed to _Ham__spam. This transformation is independent of the syntactical context in which the identifier is used.

Don't use class-private names unless you specifically want to avoid having to tell developers that want to subclass your class that they can't use certain names or risk breaking your class. Outside of published frameworks and libraries, there is little use for this feature.

The PEP 8 Python Style Guide has this to say about private name mangling:

If your class is intended to be subclassed, and you have attributes that you do not want subclasses to use, consider naming them with double leading underscores and no trailing underscores. This invokes Python's name mangling algorithm, where the name of the class is mangled into the attribute name. This helps avoid attribute name collisions should subclasses inadvertently contain attributes with the same name.

Note 1: Note that only the simple class name is used in the mangled name, so if a subclass chooses both the same class name and attribute name, you can still get name collisions.

Note 2: Name mangling can make certain uses, such as debugging and __getattr__(), less convenient. However the name mangling algorithm is well documented and easy to perform manually.

Note 3: Not everyone likes name mangling. Try to balance the need to avoid accidental name clashes with potential use by advanced callers.

public, private and protected Access Modifiers in Python, This approach isn't meant to hide anything; I just want to understand what Python does. class Parent(object):  Python - public, private and protected Access Modifiers Classical object-oriented languages, such as C++ and Java, control the access to class resources by public, private and protected keywords. Private members of a class are denied access from the environment outside the class.

The double __ attribute is changed to _ClassName__method_name which makes it more private than the semantic privacy implied by _method_name.

You can technically still get at it if you'd really like to, but presumably no one is going to do that, so for maintenance of code abstraction reasons, the method might as well be private at that point.

class Parent(object):
    def _protected(self):

    def __private(self):
        print("Is it really private?")

class Child(Parent):
    def foo(self):

    def bar(self):

c = Child()

This has the additional upside (or some would say primary upside) of allowing a method to not collide with child class method names.

Inheritance of private and protected methods in Python , is to add a prefix _ (single underscore) to it. This effectively prevents it to be accessed, unless it is from within a sub-class. Python Inheritance. Inheritance allows us to define a class that inherits all the methods and properties from another class. Parent class is the class being inherited from, also called base class. Child class is the class that inherits from another class, also called derived class.

Also PEP8 says

Use one leading underscore only for non-public methods and instance variables.

To avoid name clashes with subclasses, use two leading underscores to invoke Python's name mangling rules.

Python mangles these names with the class name: if class Foo has an attribute named __a, it cannot be accessed by Foo.__a. (An insistent user could still gain access by calling Foo._Foo__a.) Generally, double leading underscores should be used only to avoid name conflicts with attributes in classes designed to be subclassed.

You should stay away from _such_methods too, by convention. I mean you should treat them as private

Protected variable in Python, Based on access specification, variables can be public, protected and private in a class. be treated as a non-public part of the API or any Python code, whether it is a function, a method or a data member. Example 2: During Inheritance. Private, protected and public in Python. A lot of folks learn object-oriented programming with languages like C++ and Java. And while they learn, they’re told repeatedly (over and over again), that encapsulation is one of the key principles of object-oriented paradigm and that they should take advantage of it.

By declaring your data member private :


you simply can't access it from outside the class

Python supports a technique called name mangling.

This feature turns class member prefixed with two underscores into:


if you want to access it from Child() you can use: self._Parent__private()

Private Methods in Python, In this tutorial we will learn about private, public and protected data members along language, access to variables or functions can also be limited in python using the When inheritance is implemented there is a huge risk for the data to get  Access Modifiers in Python. In most of the object-oriented languages access modifiers are used to limit the access to the variables and functions of a class. Most of the languages use three types of access modifiers, they are - private, public and protected.

Although this is an old question, I encountered it and found a nice workaround.

In the case you name mangled on the parent class because you wanted to mimic a protected function, but still wanted to access the function in an easy manner on the child class.

parent_class_private_func_list = [func for func in dir(Child) if func.startswith ('_Parent__')]

for parent_private_func in parent_class_private_func_list:
        setattr(self, parent_private_func.replace("_Parent__", "_Child"), getattr(self, parent_private_func))        

The idea is manually replacing the parents function name into one fitting to the current namespace. After adding this in the init function of the child class, you can call the function in an easy manner.


Best practices for using public, protected, private?, Python doesn't have any mechanisms, that would effectively restrict you from accessing a variable or calling a member method. All of this is a  Protected variable in Python Prerequisites: Underscore ( _ ) in Python A Variable is an identifier that we assign to a memory location which is used to hold values in a computer program.

Python Access Modifiers: Private, Public and Protected, When defining class methods, we can hint that a function is protected by prefacing it with _ or we can I am strongly in favour of composition over inheritance. We should code in Python rather than MyCompanyPython. The built-in Python function super() allows us to utilize parent class methods even when overriding certain aspects of those methods in our child classes. Multiple Inheritance Multiple inheritance is when a class can inherit attributes and methods from more than one parent class.

Private, protected and public in Python (by @radekpazdera), Protected member is (in C++ and Java) accessible only from within the class and it's subclasses. But there is a method in Python to define Private: Add “__” (​double The reason is, that there should be no clashes in the inheritance chain. It is transitive in nature, which means that if class B inherits from another class A, then all the subclasses of B would automatically inherit from class A. Below is a simple example of inheritance in Python. # A Python program to demonstrate inheritance. # Base or Super class. Note object in bracket. # (Generally, object is made ancestor of

Should private or protected methods be preferred? · Issue #5 , In Python, every object has some default attributes and methods in addition to There are three types of access modifiers in Python: public, private, and protected​. The basic idea of inheritance in object-oriented programming is that a class  If the inheritance is public, everything that is aware of Base and Child is also aware that Child inherits from Base. If the inheritance is protected, only Child, and its children, are aware that they inherit from Base. If the inheritance is private, no one other than Child is aware of the inheritance. improve this answer.

  • What do you mean by "this doesn't work"?
  • I edited the original Post.
  • you have to call it this way, assume c is an instance of Child c._Parent__private()
  • Isn't it working as it should? AFAIK private methods are not inherited.…
  • I knew, it had something to do with this name mangling thing. I knew I could access to the method from outside the class by _Parent__private, but I just didn't get why I couldn't call it inside the inherited class. I didnt knew, that subclasses get their own __private(), thank you very much for this clear answer!
  • What about __getstate__() and __setstate__()? A child would not be able to inherit these methods from its parent?
  • @BoltzmannBrain: Those names contain underscores at the end too, not just at the start of the name. That's a different class of names. See the documentation I linked to.
  • Thanks, but the docs there aren't giving me much more useful info. I've moved this to another question:…
  • @Martijn: Thank you for the answer. Maybe I'm not using a pythonic style when trying to make all variables private inside a class and then use getters and setters for these private variables. Well, I should google this question about usage of private variables.