pythoninheritancecomposition

How to generalize an inherited method call and a composed method call


At work, I'm running into an issue where a piece of code takes in a class object, obj, where the object can be one of multiple classes. The code makes the following call:

obj.compute()

For one of the classes, MyClass, I made a refactorization from using inheritance to composition. Previously, that class would have inherited compute() from one of its parent classes, but now it's accessed using obj.sub.compute(), so this breaks the above call because the rest of the classes still have a compute() method.

I can think of a couple solutions to this problem:

  1. In MyClass, after initialization the composition in its constructor, we can do:
self.compute = self.sub.compute
  1. In the call sites for obj.compute(), we can do a type check. When obj is MyClass, we can call obj.sub.compute()

I don't know how appropriate these solutions are? Are there are alternatives?


Solution

  • Your refactored class should define compute to comply with the expected API.

    class MyClass:
        def __init__(self, ...):
            self.sub = ...
    
        def compute(self):
            return self.sub.compute()
    

    Defining an instance attribute named compute is not the same as providing a method named compute, and it should not be the job of the caller to deal with a non-compliant object.