[Python] How to tell Python which constructor to use to instantiate subclasses? [duplicate]

Discussão em 'Python' iniciado por Stack, Janeiro 30, 2025.

  1. Stack

    Stack Membro Participativo

    I am in the following situation: I have a type A, two subtypes B and C of A, a function f of type A -> A that is such that

    • for any B object x, f(x) is of type B;
    • for any C object x, f(x) is of type C.

    I would like a Python code compliant with this data. I tried the following:

    class A:
    def __init__(self, args):
    ...

    def f(self) -> A:
    args = ...
    return A(args)

    class B(A):
    pass

    class C(A):
    pass


    and tested

    x = B(...)
    y = x.f()
    assert isinstance(y, B)


    and of course, the assert raises an exception, and I now understand that I should have predicted it (the only f that is defined creates an object of type A...).

    I could solve my problem just by define a method f for both B and C, that would be exactly the same, except for the constructor call in the last line of the method. It doesn't seem very smart to do that. Is there a smarter way?

    According an answer of this question, which is not the accepted one, the problem could be resolved by replacing

    return A(args)

    by

    return type(self)(args).

    It seems to be working; is it the preferred way to solve the problem?

    Continue reading...

Compartilhe esta Página