I am learning about inheritance mechanisms in Python and i want to make some variables that are automatically calculated inside the child __init_() function, but the problem is that i want to make yet another class in which the variable will be overwriten. And i dont want those variables to be calculated twice, once in parent and then in child. So, is the example below correct?
class Shape(object):
def __init__(self, x, y):
self.x = x
self.y = y
def getcenter(self):
return self.x, self.y
class Square(Shape):
def __init__(self, x, y, a):
super().__init__(x,y)
self.a = a
self.perimeter = 4*a
self.field = a*a
class Rectangle(Square):
def __init__(self, x, y, a, b):
super().__init__(x, y, a)
self.perimeter = (2*a) + (2*b)
self.field = a*b
Well, ignoring that your above would actually be better to have Square subclass Rectangle, normally that type of logic would be moved into a new function overridden by the subclass.
class Square:
def __init__(self, a):
self.a = a
self.calculate_perimeter()
def calculate_perimeter(self):
self.perimeter = self.a * 4
class Rectangle(Square):
def __init__(self, a, b):
self.b = b
super().__init__(a)
# automatically called by the parent class
def calculate_perimeter(self):
self.perimeter = self.a * 2 + self.b * 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With