0

Python magic method __class__

class C1: a=4 class C2: a = 5 c = C1() c.__class__ = C2 print(c.a) Above code is one of the quizzes in the challenge. The answer is 5, which means instance c got 5 from class C2. I wanted to know how the instance can call the method __class__ if it’s not written in class C2. I remember from other codes that magic method __init__ was written in class to be called. Why the method __class__ wouldn’t need to be written up?

15th Nov 2021, 10:27 PM
Han Lee
Han Lee - avatar
3 Réponses
+ 3
Every object has __class__ attribute(may be few exceptions) ,which contains the class from which the object is created(or instantiated) and the code modifies the __class__ attribute value to other class and hence this object now will be the instance of the changed class ADDITIONAL INFORMATION(USEFUL): https://www.honeybadger.io/blog/JUMP_LINK__&&__python__&&__JUMP_LINK-instantiation-metaclass/
16th Nov 2021, 7:01 AM
Prabhas Koya
+ 1
c = None (class C1: ... ; c = C1()) == (class C1: ... ; c.__class__ = C1) they mean the same thing. everything in python is an object, meaning it has a class. everything in python has that ".__class__" attribute and it deals with the lower levels of python, noted by the double underscore. Everything is part of a base class, and that base class has all these main methods, including __class__ and __init__. Everything made from this class, (everything in pthon) inherits these attributes. Look into classes and subclasses for more info!
15th Nov 2021, 10:53 PM
Slick
Slick - avatar
+ 1
My two cents on this topic. The shown example gives that output, because "a" is a class variable, not an instance variable. Consider this: >>> class C1: ... a=1 ... def __init__(self): ... self.b=11 ... >>> class C2: ... a=2 ... def __init__(self): ... self.b=22 ... >>> c = C1() >>> print(c.a, c.b) 1 11 >>> c.__class__ = C2 >>> print(c.a, c.b) 2 11 >>>
17th Nov 2021, 11:29 AM
Евгений
Евгений - avatar