Python: why does first class print 8, but secont doesn't? | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
+ 2

Python: why does first class print 8, but secont doesn't?

class A: def __init__(a,b,c): print(b) class B: def __init__(a,b,c,d): print(c) A(8,3) B(8,3)

21st Jun 2020, 4:54 PM
Paolo De Nictolis
Paolo De Nictolis - avatar
3 Respuestas
+ 2
Here...the 'a' is used instead of 'self'. Class 'B's __init__ expects 3 arguments...but you only passing 2.
21st Jun 2020, 5:09 PM
rodwynnejones
rodwynnejones - avatar
+ 2
Every class instance method has 1st argument of the self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class. You can use any arbitrary name for the current instance. In your example 'a' is instance. So in class A, b and c are arguments you have to pass for instance intialization. For class B you have to pass b, c and d to __init__ but you have passed only two arguments, so you are getting error. Run below code and check the arguments values. I have added code to print the type of instance so you could differentiate the instance parameter. class A: def __init__(a,b,c): print(type(a),b,c) class B: def __init__(a,b,c,d): print(type(a),b,c,d) A(8,3) B(9,4,1)
21st Jun 2020, 5:39 PM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar
0
class A: def __init__(a,b,c): print(a,b,c) class B: def __init__(a,b,c,d): print(a,b,c,d) A(8,3) B(9,4,1) print("========================") #if you run above code then you will see the both instance are constructed at same memory location. You may confused for the same memory location. The reason for that is you are not assigning created instance to any variable so the temporary object has been created and destroyed. While executing line A(8,3) python interpreter first create temporary instance of class A at some memory location and destroy it. When interpreter comes to line B(9,4,1) it got same location for the creation of class B's temporary instance. #if you run above code, then you will see the both instances are constructed at the same memory location. You may confuse for the same memory location. The reason for that is you are not assigning created instance to any variable so the temporary object has been created #Example: a = A(8,3) b = B(9,4,1)
21st Jun 2020, 6:19 PM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar