在Python中将派生类转换为基类

问题描述 投票:0回答:2
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")

我想从

option
对象中获取
order

option = order as Option
order.option
python python-3.x casting polymorphism downcast
2个回答
0
投票

这与 Python 中的继承工作不太一样。

一种选择是使用类方法来重新创建 Option 对象。

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

我必须承认,我没有看到这应该有用的具体示例。


0
投票

对于那些出于相同问题但不特定于此示例而登陆此处的人,请使用

super(...)
。它通常在类成员函数中使用(检查使用 super 的正确方法(参数传递) ),但这里有一些在课堂外使用它的示例:

# create some classes with inheritance to test
class A:
    x="a"
class B(A):
    x="b"
class C(B):
    x="c"
class D(C):
    x="d"
    
assert A().x=='a'
assert B().x=='b'
assert super(B, B()).x=='a' # << cast B to A
assert super(C, C()).x=='b' # << cast C to B
assert super(B, C()).x=='a' # << cast C to A
assert super(D, D()).x=='c' # << cast D to C
assert super(C, D()).x=='b' # << cast D to B
assert super(B, D()).x=='a' # << cast D to A

# create an unrelated class
class X:
    x="X"

# cast C to X fails because C is unrelated to X
try:
    super(X, B())
except TypeError:
    pass

# Casting to parent via "__bases__"
assert A.__bases__==(object,)
assert B.__bases__==(A,)
assert C.__bases__==(B,)
assert D.__bases__==(C,)
assert super(C.__bases__[0], C()).x=='a' # << cast C to A
assert super(D.__bases__[0], D()).x=='b' # << cast D to B
assert super(D.__bases__[0].__bases__[0], D()).x=='a' # << cast D to A

# Note that "type(super(...))" returns "super" instead of the class name
# Not sure how to fix that (maybe in combination with __bases__?)
assert type(super(B, B()))==super
© www.soinside.com 2019 - 2024. All rights reserved.