Python - what does ' obj.__n = 3 ' do in this code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Python - what does ' obj.__n = 3 ' do in this code?

class Myclass: def __init__(self, n=1): self.__n = n def val_n(self): return self.__n obj = Myclass("zzz") print(obj.val_n()) # outputs zzz obj.__n = 3 # What does this do? print(obj.__n) # outputs 3 as expected print(obj.val_n()) # outputs zzz 1) What does obj.__n = 3 do to the class? It doesn't seem to affect the value of the n attribute... 2) Why do we need the double underscore before the n in self.__n?

30th Sep 2020, 10:23 PM
Solus
Solus - avatar
3 Answers
+ 1
A double underscore prefix causes the Python interpreter to rewrite the attribute name in order to avoid naming conflicts in subclasses. 1)obj.__n does not refferering to Myclass.__n. But it creating a new variable. see this by comment #obj. __n = 3 print(obj.__n) is error now. 2) for naming conflicts in subclasses... It is not accessible out of class..
30th Sep 2020, 10:53 PM
Jayakrishna 🇮🇳
0
Jayakrishna🇮🇳 I see, so obj.__n = 3 does NOT mean assigning 4 to self.__n = n. Rather, obj.__n = 3 is a new variable outside of the class. I'm still a bit confused about the dot in obj.__n. Is obj.__n the name of an integer variable? --> why does it contain a dot/period? From my understanding, a variable name CANNOT contain a period...
1st Oct 2020, 9:41 PM
Solus
Solus - avatar
0
(ohh.. I just now seen this post) obj.__n here obj is object created for class Myclass by statement obj = Myclass("zzz") This calls Myclass constructor and creates a object and stored in obj. now with this obj, you can call that class methods and data properties by period operator like obj.n means reffering the data value n of object obj.val_n() means calling val_n() method of obj object... The period is called derefferncing operator..
4th Oct 2020, 6:56 PM
Jayakrishna 🇮🇳