Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to overwrite variables in child classes that need to be calculated in __init__()?

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
like image 495
Radek Lejba Avatar asked Mar 11 '23 20:03

Radek Lejba


1 Answers

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
like image 144
cwallenpoole Avatar answered Apr 26 '23 01:04

cwallenpoole