使用基类实例实例化派生类?

时间:2020-09-02 17:28:24

标签: python-3.x

我有一个用于基类(A)的工厂方法。它需要一个A实例来确定要实例化哪个派生类。 (V3 +)使用Python的方式是什么?

class A():

    @classmethod
    def factory(a, b, c):
        foo=A(a,b,c)
        #...use foo to determine that B is the needed subclass.
        return B(foo)

    def __init__(self, a, b, c):
        #  calculations on a, b, c produce several instance attributes
        self.m = calculated_m
        #...
        self.z = calculated_z

class B(A):
    def __init__(self, instance_of_A):
        super(B, self).__init__(?)         # How to construct superclass (A) given an instance of A?

1 个答案:

答案 0 :(得分:0)

您在这里:

class A():

    @classmethod
    def factory(cls, a, b, c): # first argument of a classmethod is the class on which it's called
        return cls(a, b, c)

    def __init__(self, a, b, c):
        #  calculations on a, b, c produce several instance attributes
        self.m = calculated_m
        #...
        self.z = calculated_z

class B(A):
    def __init__(self, a, b, c):  # example for a subclass with the same signature
        super(B, self).__init__(a, b, c)

class C(A):
    def __init__(self, x, y):  # example for a subclass with different constructor args
        super(B, self).__init__(x+y, x*y, 2*x)
    @classmethod
    def factory(cls, x, y):
        return cls(x, y)

用法:

foo = A.factory(a, b, c)  # this will call A.factory
bar = B.factory(a, b, c)  # this also
baz = C.factory(x, y)  # this will call C.factory

也许您可以将factory方法重命名为get_instance,因为工厂通常是专门用于创建其他类对象的类。

如果您还有疑问,请写评论