python - how to specify return type hint for a method that returns a new object

32 Views Asked by At

I'll first introduce my situation and then ask the question.

So I already have the following code written and can not be changed:

class A:
    def __init__(self, number: int, letter: str):
        self.number = number
        self.letter = letter

    @classmethod
    def create_new(cls, number: int, letter: str):
        return cls(number, letter)

As you can see, the method create_new can create new objects from given attributes. Obviously, in real life, the class itself isn't called "A" and the methods are far more complicated. For the sake of the example, I distilled the staff that matters.

Now, I want to add the following method to the class:

    def create_new_with_different_number(self, number: int):
        return self.create_new(number, self.letter)

in order to allow the user to create new, almost-identical object, with only one attribute changed (in this example - the same object only with different number).

Is there a way for me to precisely indicate the return type of create_new_with_different_number? Something like:

    def create_new_with_different_number(self, number: int) -> A:
        return self.create_new(number, self.letter)

won't work, since "A" is not defined yet when the method is being defined.

P.S: I know the situation might sound complex and seem like a bad design, but it is what it is and I need to only add my method, not change the existing ones.

0

There are 0 best solutions below