+ 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!!!
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()
+ 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
0
Parent.__init__() sorry for this error.
0
You override the method in class B. Use super().method() you can get what you want.
- 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())