Jul-18-2019, 12:21 PM
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:
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().
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().
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures