0

As I have been told, placing a double underscore in front of a method makes it private in Python. Thus,

class Test:
    def __private_function(self):
        print("This function is private!")
    def public_function(self):
        print("This function is public!")

However, it seems like a variety of methods like "init" and "mro" among others, are completely public despite the double underscore in front of their names. In other words:

class Test:
    def __init__(self):
        print("This function is public!")

Why does this occur?

martineau
  • 119,623
  • 25
  • 170
  • 301
Dude156
  • 158
  • 1
  • 12
  • 1
    Python had no private methods, just a convention on how to name methods that **should** be used privately. – Klaus D. Apr 18 '20 at 01:43
  • "As I have been told, placing a double underscore in front of a method makes it private in Python." You've been misinformed, *Python doesn't have private variables*. Leading double-underscores *is for name-mangling, to prevent accidental name collisions in subclasses*. This will not occur if you have leading **and** trailing double-underscores, so-called "dunder" methods, which are for specific parts of the python data model. You use a *single* underscore, as a convention, to signal attributes that are not part of the public API. – juanpa.arrivillaga Apr 18 '20 at 01:45
  • 1
    Does this answer your question? [What is the meaning of a single and a double underscore before an object name?](https://stackoverflow.com/questions/1301346/what-is-the-meaning-of-a-single-and-a-double-underscore-before-an-object-name) – Harshal Parekh Apr 18 '20 at 01:48
  • 1
    [Here's the relevant part of the documentation](https://docs.python.org/3/reference/lexical_analysis.html#reserved-classes-of-identifiers) – Patrick Haugh Apr 18 '20 at 01:50
  • 1
    Does this answer your question? [Why do some functions have underscores "\_\_" before and after the function name?](https://stackoverflow.com/questions/8689964/why-do-some-functions-have-underscores-before-and-after-the-function-name) – izhang05 Apr 18 '20 at 02:01

1 Answers1

2

A double leading underscore does not actually make a method private. A single leading underscore hints that the method should be for internal use only, but is not enforced by python.

__init__

has a double leading and trailing underscore which means that it is a magic method that is reserved for special use by python. You should never name a method with double leading and trailing underscores.

izhang05
  • 744
  • 2
  • 11
  • 26
  • Yes for sure! Sorry about that! Would you mind also clarifying what exactly entails a magic method? Is it like a python-builtin or something? – Dude156 Apr 18 '20 at 02:03
  • 1
    Yes, they are builtin and are called by Python internally – izhang05 Apr 18 '20 at 02:08