Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between using self._variable and just self.variable in the constructor in Python

for Example if I create a class Point.

class Point:

def__init__(self, x, y):
    self._x = x
    self._y = y 

and

class Point:

def__init__(self, x, y):
    self.x = x
    self.y = y 

what is the difference in the use of self._x and just self.x.

like image 607
Confused101 Avatar asked Oct 25 '25 04:10

Confused101


1 Answers

The single underscore is just a naming convention to state that the property should be considered "semi-private" (similarly double underscore means "private"), but it doesn't have a semantic difference: both versions of the code should behave exactly the same. According to PEP-8:

_single_leading_underscore : weak "internal use" indicator. E.g. from M import * does not import objects whose name starts with an underscore.

single_trailing_underscore_ : used by convention to avoid conflicts with a Python keyword.

__double_leading_underscore : when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo).

__double_leading_and_trailing_underscore__ : "magic" objects or attributes that live in user-controlled namespaces. E.g. __init__ , __import__ or __file__ . Never invent such names; only use them as documented.

If, for some reason, you have a variable prefixed by an underscore and it is acceptable to publicly access this variable, then it is a good practice to include the name of this variable in your module's __all__ list. This serves as a form of in-code documentation.

like image 137
Óscar López Avatar answered Oct 27 '25 02:10

Óscar López