用基类的实例实例化派生类



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

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?

开始:

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,因为工厂通常是专门用于创建其他类的对象的类。

如果你还有问题,写一条评论

最新更新