0

Intuitively this seems impossible, but here goes.

I am importing a class from a python module, where it has a static method that returns a new instance of the class and does some stuff to that instance, let's just call this method make_instance. I am trying to create a custom class with some overridden functionality that inherits from this class. Here comes the problem, there seems to be no way of overriding the make_instance in a way so that it returns my subclass instead of the super class.

Here's a minimal example:

# Note that I cannot edit this class, nor see the contents of this class, as it is from a python module
class SuperClass:
    @staticmethod
    def make_instance(number) -> SuperClass:
        obj = SuperClass()
        obj.number = number * 2
        return obj

class SubClass(SuperClass):
    @staticmethod
    def make_instance(number) -> SubClass:
        return super().make_instance(number) # Returns a SuperClass object

    # Additional functionality of the subclass

Is there potentially any way of achieving this? If not is there any other suggestions that could help with this kind of situation? Thanks.

DaNubCoding
  • 320
  • 2
  • 11
  • 1
    You may want to [prefer composition over inheritance](https://stackoverflow.com/questions/49002/prefer-composition-over-inheritance) in this situation. If the only way to initialize the parent class is through it's `make_instance` method, then inheritance doesn't have much appeal. – Woodford Jan 20 '23 at 22:57
  • @Woodford In that case, would I have to define every single one of the superclass's methods in the new class in order to get them? – DaNubCoding Jan 20 '23 at 23:02
  • You seem to be trying to inherit from a built in class which does not have s public constructor. Interesting. Maybe it would be easier to give you an answer if you were to say exactly which built in class this was about. – zvone Jan 20 '23 at 23:02
  • @zvone It's the Texture class from pygame._sdl2.video, I don't think that changes anything though. The Texture class does have a constructor, it's just that it would be much more convenient to use the staticmethod as it has very useful functionality. – DaNubCoding Jan 20 '23 at 23:07

1 Answers1

0

As it seems like there isn't a way to achieve this, I've resorted to using the fishhook module to create method hooks for all the methods that need to be inherited, instead of inheriting and then trying to override the problematic static method.

DaNubCoding
  • 320
  • 2
  • 11