0

I have a class that has an attribute as an object from another class. A third class inherits from the first class, and in there, I want to override the attribute's method ...

class Car:
    def __init__(self, door):
        self.door = door

class Door:
    def __init__(self, color):
        self.color = color
    def change_color(self):
        pass

class CarConstruct(Car):
    def __init__(self):
        super(CarConstruct, self).__init__(Door('red'))
        # Here, I want to override self.door.change_color method

What is the best way to override in such a situation?

M. Zidan
  • 156
  • 9
  • 2
    What problem are you trying to solve with thism – Klaus D. Mar 03 '19 at 20:03
  • You can't override other objects' methods. – user2357112 Mar 03 '19 at 20:05
  • @klausD. A problem in a GUI. The GUI uses a template where its ´self.content´ is class that has a ´FigureCanvasQTAgg´ in it, which is connected to a mouse event. In the main GUI class, I want to override (define) this mouse clicking event – M. Zidan Mar 03 '19 at 20:14
  • 1
    The proper way to override a method is with a subclass. Define a subclass of `Door` with the appropriate method, and pass an instance of *that* class to `super().__init__`. – chepner Mar 03 '19 at 20:42

1 Answers1

1

This technique is called "monkey patching". In general it should be avoided, because it makes the code very hard to understand and reason about. Avoid it unless you have a very good cause. One of the good causes might be to mock a method in unit tests.

If you still want to monkey patch just one method on one object self.door - check out this answer.

battlmonstr
  • 5,841
  • 1
  • 23
  • 33
  • If you have found a monkey patch in one of two thousand tests at a place totally unrelated to the problem you where debugging and after three day of head scratching, then you know how "good" your case is. – Klaus D. Mar 03 '19 at 21:29
  • lol. That's the price you have to pay for using a dynamic programming language :) – battlmonstr Mar 03 '19 at 21:34
  • …without some discipline. ;-) – Klaus D. Mar 03 '19 at 21:46