pythonobject-oriented-analysis

Inheritance: how to call method of parent class?


I made following 3 classes. India is parent class of States and States is parent class of District. I define 1 object of District class. When I try to run method of India class it gives an error. Please help me how to run it.

class India:
    def __init__(self):
        print("Country is India")
    def functionofindia(number):
        rvalue=number*2
        return rvalue   

    
class States(India):
    def __init__(self,nameofstate):
        super().__init__()
        print("state is {}".format(nameofstate))


class District(States):
    def __init__(self,nameofstate, nameofdistrict):
        super().__init__(nameofstate)
        print("District is {}".format(nameofdistrict))


HP=District("abc","xyz")
print(HP.functionofindia(2))

The Error is:

Country is India
state is abc
District is xyz
Traceback (most recent call last):
  File "c:\Users\DELL\OneDrive\Desktop\practice\oops.py", line 23, in <module>
    print(HP.functionofindia(2))
TypeError: functionofindia() takes 1 positional argument but 2 were given

Solution

  • To use a class method like this you should pass self as the first argument in the method definition. So your class India becomes:

    class India:
        def __init__(self):
            print("Country is India")
        def functionofindia(self, number):
            rvalue=number*2
            return rvalue
    

    When the method is not relevant to any attribute of the class, you could also replace it with a static method. See more about static methods here. India with a static method:

    class India:
        def __init__(self):
            print("Country is India")
    
        @staticmethod
        def functionofindia(number):
            rvalue=number*2
            return rvalue