+ 1

class Myclass : def __init__(self,val): self .__n=val obj=Myclass(0) obj.__n=1 print (obj._Myclass__n )

How output of this code is 0

13th Apr 2023, 4:23 AM
Somvir Dhaka
Somvir Dhaka - avatar
6 ответов
+ 7
a class named Myclass is defined, which has a constructor __init__ that initializes an instance variable __n with the value passed as argument. Then an object obj is created with the argument 0. Next, the code tries to set the value of __n to 1 using the syntax obj.__n=1. However, since __n is a private variable (indicated by the double underscores), Python interprets this as a new instance variable being created and added to obj, rather than changing the value of the existing __n variable. Finally, the code prints the value of obj._Myclass__n. Here, the syntax _Myclass__n is used to access the private variable __n of the Myclass class. This works because Python actually stores private variables with a name that includes the class name (with a leading underscore), so the variable can still be accessed from outside the class, but the syntax is a bit more cumbersome. Since the original value of obj.__n was never changed (instead, a new instance variable was created), its value remains 0. Therefore, it is 0.
13th Apr 2023, 7:14 AM
Sadaam Linux
Sadaam Linux - avatar
+ 4
obj is assigned to Myclass with an attribute value of 0, and because the __init__ method assigns this argument value to a name with a double underscore __n the interpreter distorts it in _Myclass__n which is printed.
13th Apr 2023, 6:07 AM
Solo
Solo - avatar
+ 2
Because if you want to change the value you need a set function for __n
13th Apr 2023, 6:52 AM
KfirWe
KfirWe - avatar
0
Great
13th Apr 2023, 7:30 AM
Somvir Dhaka
Somvir Dhaka - avatar
0
Sadaam Linux Is it a ChatGPT generated answer?
14th Apr 2023, 2:29 PM
Евгений
Евгений - avatar
0
This topic is covered in the lesson 77.1 Data Hiding of the Python Core course.
14th Apr 2023, 2:34 PM
Евгений
Евгений - avatar