[英]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")
我想從order
object 中獲得option
。
option = order as Option
order.option
這不是真的像 inheritance 在 Python 中工作。
一種選擇是使用 class 方法重新創建選項 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
我必須承認,我沒有看到這應該有用的具體示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.