Confused101
Confused101

Reputation: 43

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.

Upvotes: 4

Views: 3515

Answers (1)

Óscar López
Óscar López

Reputation: 236004

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.

Upvotes: 6

Related Questions