where did I go wrong in this code for it to give me 1instead of 2? class A: def method(self): print (1) class B(A): def method(self): print(2) B().method() | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
+ 1

where did I go wrong in this code for it to give me 1instead of 2? class A: def method(self): print (1) class B(A): def method(self): print(2) B().method()

that printed 1 on my 3.5 python,but I got marked wrong,went for a hint and gave the answer as 2!!!

1st Aug 2016, 12:03 PM
winston j.c mhango
winston j.c mhango - avatar
5 Réponses
+ 5
pl remember subclass methods override superclass methods. hence we need to use 'super()' to call superclass method. Shown in this example: class A: def method(self): print (1) class B(A): def method(self): print(2) print("calling superclass method") super().method() B().method()
1st Aug 2016, 12:31 PM
Chitra Jha
Chitra Jha - avatar
+ 2
are you sure you had that exact code with no typos? if you'd spelt method wrong in class B it would not have overwritten the method, so when you called it, you'd get the one in class A
9th Sep 2016, 2:35 PM
Phil
Phil - avatar
0
Parent.__init__() sorry for this error.
22nd Aug 2016, 2:23 PM
Miguel Lora
Miguel Lora - avatar
0
You override the method in class B. Use super().method() you can get what you want.
7th Sep 2016, 1:05 PM
杨正龙
杨正龙 - avatar
- 2
As I understand: "class A": is a "Parent Class"; "class B" : "is the children". class Parent(): def __unit__(self, ParentProperty): self. ParentProperty= ParentProperty class Children(Parent): def __init__(self): Parent.__unit__(self,"for_parent_property_data") print(Children())
22nd Aug 2016, 2:21 PM
Miguel Lora
Miguel Lora - avatar