Varun KT
Varun KT

Reputation: 21

method skipped when Inheritance used in Python

Secondclass inherits from Firstclass. So all methods defined in Firstclass should be available in Secondclass. Both the classes have the same methods, but with different arguments.Here, function method1 is called by passing a string as an argument.

class firstclass():
   def method1(self,somestring):     # method1 which has a string as a parameter
      print("method1 is invoked") 

class secondclass(firstclass):       # Secondclass inherits firstclass
   def method1(self):                # method1 of second class which has no parameters
      print("method2 is invoked")

def main():
   a=firstclass()      # creates object for the first class
   b=secondclass()     # creates object for the second class 
   b.method1("abc")    # which method will it call ???

main()

When the function method1 is called using object of secondclass, why is it not printing "method1 is invoked" ?

Upvotes: 2

Views: 105

Answers (2)

Jordan A.
Jordan A.

Reputation: 384

When you define method1 in secondclass you overwrite the inherited method from firstclass. Meaning the method method1 in secondclass is the one that you have defined in that class, not the one that is inherited.

So when you call method1 as a method of secondclass, you will get "method2 invoked" because that is what you have overwritten the method to do, rather than follow the inherited method from firstclass.

Edit: mabac is correct, since method1 from secondclass doesn't take any parameters, there will be an exception raised because the parameter of the method is "abc"

Upvotes: 1

SiHa
SiHa

Reputation: 8411

If you were expecting both methods to be called, you need to make use of super() to call the method in firstclass.

  • As mentioned in the linked docs, in order for this to happen, firstclass needs to be a new-style class, so should inherit from object.

  • Also, as commented above, your method in firstclass requires a parameter, so I have passed in a dummy:

  • Note also that I have changed the class names to CapWords style - see PEP8

class FirstClass(object):
   def method1(self,somestring):
        print('method1 is invoked') 

class SecondClass(FirstClass):
   def method1(self): 
        super(SecondClass, self).method1('dummy_string')
        print('method2 is invoked')

def main():
   a=FirstClass()
   b=SecondClass()
   b.method1()

main()

Output:

method1 is invoked
method2 is invoked

Upvotes: 0

Related Questions