Python Forum
error in constructor overriding in python3 - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: error in constructor overriding in python3 (/thread-19884.html)



error in constructor overriding in python3 - srm - Jul-18-2019

class Baseclass1:
    def __init__(self,x,y):
       self.x=x
       self.y=y
       print(self.x+self.y)
class Derived(Baseclass1):
    

    def cmethod(self):
        
        Baseclass1.__init__(self,x,y)#Base constructor called with class name
        print(self.x * self.y)
            
ob=Derived(4,5)
ob.cmethod()
Error:
Traceback (most recent call last): File "C:/Python37/understandingConstructor.py", line 33, in <module> ob.cmethod() File "C:/Python37/understandingConstructor.py", line 29, in cmethod Baseclass1.__init__(self,x,y)#Base constructor called with class name NameError: name 'x' is not defined
here I am not able to override construcor of the base class and getting error.probably my code is wrong...but can anyone explain how constructor overriding code in python with proper example...


RE: error in constructor overriding in python3 - ichabod801 - Jul-18-2019

First of all, the error has nothing to do with overriding. The error is because x and y are not defined in cmethod. The only place they are defined is in BaseClass1.__init__, where they are defined as parameters. If you want to access the instance values of x and y from within cmethod, you need to use self.x and self.y, as you did in BaseClass1.__init__.

Second of all, you are not overriding anything. When you override a method, it has the same name. That makes the overridden version be called for the derived class. It would be more like this:

class Plus(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def act(self):
        return x + y
class Minus(Plus):
    def act(self)
        return x - y
Output:
>>> p = Plus(8, 1) >>> m = Minus(8, 1) >>> p.act() 9 >>> m.act() 7
When the Minus instance m is created, it uses the derivied __init__ method to assign x and y. But when m.act is called, it uses the overridden act method to subtract instead of adding.

So you example is a bit odd. By the time you call Derived.cmethod, the instance has already been initialized using the __init__ method inherited from BaseClass1. So it's not clear why you would call __init__ again. Also, if you are in an overridden method, and you want to call the parent class's method, you generally use super().