+ 2
Python class member variable
I saw this following question on Python quiz. class Test: def __init__(self, v = 1): self.__num = v def get_num(self): return self.__num t = Test(2) t.__num = 3 print(t.get_num()) The output of this code is 2. But my understanding says it should be 3. Can somebody explain why is this so?
5 odpowiedzi
+ 3
I got the answer myself. If you declare a member variable with two underscores before it, python interpreter does something called 'name mangling'. Because of this, the __num is changed to _Test__name. If I change my code like the following.
class Test:
def __init__(self, v = 1):
self.__num = v
def get_num(self):
return self.__num
t = Test(2)
t._Test__num = 3
print(t.get_num())
It prints 3 as expected.
I reffered the following link
https://hackernoon.com/understanding-the-underscore-of-python-309d1a029edc
+ 3
That's interesting, I never knew that!
+ 2
The reason that it is returning 2 is because the variable num is private, meaning that it can't be called from outside the class. Because of this, the only way that you can set num without using a setter method is by setting it when the object is created.
+ 2
@Faisal, Thanks for the clarification. So when I assigned t.__num = 3, it has not updated the actual __num member but another member variable with same name. If I print (t.__num), it prints 3. So in python it is possible to have two members variables with the same name?
+ 1
Huh, not too sure about that. I think it may be because of what you're using to return the variable, as the getter method may only return the set variable and explicitly referring to the variable may return the value that you have set it. Still not sure about that though, sorry!