简体   繁体   中英

Convert derived class to base class in Python

class Option:
    order_type: str
    pair: str

    def __init__(self, pair, order_type) -> None:
        self.order_type = order_type
        self.pair = pair

class Order(Option):

    price: float
    quantity: float
    
    def __init__(self, pair, order_type, price, quantity) -> None:
        Option.__init__(self, pair, order_type)
        self.price = price
        self.quantity = quantity


order = Order("btcusdt", "sell", "1", "1")

I want to get option from order object like.

option = order as Option
order.option

This is not really like inheritance works in Python.

One option would be to have a class method te recreate the Option object.

class Option:
    order_type: str
    pair: str

    def __init__(self, pair, order_type) -> None:
        self.order_type = order_type
        self.pair = pair

    @classmethod
    def from_order(cls, the_order):
        the_obj = cls(the_order.pair, the_order.order_type)
        return the_obj


class Order(Option):

    price: float
    quantity: float

    def __init__(self, pair, order_type, price, quantity) -> None:
        Option.__init__(self, pair, order_type)
        self.price = price
        self.quantity = quantity

I must admit that I don't see concrete example where this should be usefull.

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