[Python] How do I instantiate a subclass from a superclass instance in Python? [closed]

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

  1. Stack

    Stack Membro Participativo

    I want to achieve this effect, ideally without much boilerplate:

    class Vehicle:
    def __init__(self, license_plate) -> None:
    self.license_plate = license_plate
    # Several other fields...

    register(self) # Expensive!

    class Truck(Vehicle):
    def __init__(self, v: Vehicle, commercial_license) -> None:
    # Move all of v's fields into self without calling Vehicle.__init__ ...

    self.commercial_license = commercial_license

    register_commercial(self)


    (For example, in C++, I could call the superclass's default move constructor in the subclass constructor's initializer list.)

    Continue reading...

Compartilhe esta Página