简体   繁体   中英

Python static method return subclass instead of superclass

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM