Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

By convention of python, can subclass access parent's variables whose names start with a single leading underscore "_"?

Tags:

python

oop

In python, by convention, a leading underscore in a variable's name (e.g., _var) is to indicate it is for internal use. However, should this "internal" variable still be revisable by subclasses (by convention)?

In other words, is _var private or protected?

like image 583
s.p Avatar asked Sep 05 '25 13:09

s.p


1 Answers

Pep 8 has some useful bits.

TL;DR :: There's no true private or protected modifiers in Python. You can think of attributes as being non-public which is by convention, but not strictly enforced. Attributes can be buried a little deeper by using a double underscore (ex.: __name) at the beginning, but this has some issues(/is controversial?). (See notes.)

From PEP ocho:

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. Note: there is some controversy about the use of __names (see below).

And then, further on this:

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.

like image 130
captnsupremo Avatar answered Sep 09 '25 18:09

captnsupremo