So when I call the variables from the __init__
, are there any differences between using self.
and self._
? For example, it I define a variable x in __init__
as self._x
, when I need to call it in other functions, is it possible to call it by self.x
and self._x
? This confused me a lot, thanks.
Asked
Active
Viewed 34 times
1

Hui Ting Ko
- 51
- 7
-
3[The meaning of a single- and a double-underscore before an object name in Python](http://stackoverflow.com/questions/1301346/the-meaning-of-a-single-and-a-double-underscore-before-an-object-name-in-python) – Jonathan Lonowski Nov 14 '15 at 01:12
-
The `_` is part of the property's name, along with the `x`, so `self.x` and `self._x` are entirely distinct from each other. – Jonathan Lonowski Nov 14 '15 at 01:20
-
so in this case, if the variable in `__init__` is called `self._x`, I can only call it `self._x` in other functions and vice versa? – Hui Ting Ko Nov 14 '15 at 02:20
-
@JonathanLonowski, The attribute's name. – Mike Graham Nov 14 '15 at 03:39
-
@HuiTingKo, `self._x` works, at a technical level, the same as `self.x`. The difference is purely one of convention for programmers. – Mike Graham Nov 14 '15 at 03:40
-
@MikeGraham, so it is correct to use `self._x` and `self.x` to call it if the x is assign to `self._x` only in `__init__` – Hui Ting Ko Nov 14 '15 at 10:02
-
@HuiTingKo, I can't understand what you are saying – Mike Graham Nov 16 '15 at 00:56
-
@MikeGraham, so if there is a variable called `self._x` under the `__init__` function and I want to use it in other functions, can I use both `self._x` and `self.x`? – Hui Ting Ko Nov 16 '15 at 04:56
-
@HuiTingKo, No, `self._x` is `self._x`. It's completely unrelated to `self.x`. The difference between `self.x` and `self._x` is the same as the difference between `self.y` and `self.z` -- they're just different. Python doesn't magically convert at all. `self._x` doesn't really get special, magic treatment. – Mike Graham Nov 16 '15 at 22:36