someman112
someman112

Reputation: 121

Inheritance and Private attributes in Python

class Parent:
    def __init__(self):
        self._lst = []


class Child(Parent):
    def __init__(self):
        super().__init__()

Considering the code above, say I wanted to implement a method in the Child class, am I allowed to used self._lst (which is a private attribute initialized in the Parent Class) for this method? In other words, am I allowed to access private attributes that are initialized in the Parent Class through Subclasses?

Upvotes: 2

Views: 1260

Answers (1)

linger1109
linger1109

Reputation: 520

In python, truly private attributes / methods don't exist. There are only naming conventions. What this means is if an attribute / method has its name beginning with one underscore, it can still be accessed from anywhere, just like regular attributes / methods. The only thing that this does is serve as a reminder to yourself and let other developers know that this attribute was not meant to be accessed from the outside.

To answer your question, yes, you can use _lst in the function. Even in languages that do have real access modifiers, there is frequently a different keyword to distinguish attributes not accessible from anywhere vs those that are not accessible anywhere but derived classes. In python, this is generally signified with a double underscore (__) vs a single underscore (_). Double underscores are not meant to be accessed from anywhere, while single underscores can be accessed by derived classes. See here for more information.

Upvotes: 4

Related Questions