Python 3.x 是否用基类的实例实例化派生类?

Python 3.x 是否用基类的实例实例化派生类?,python-3.x,Python 3.x,我有一个基类(a)的工厂方法。它需要一个实例来确定实例化哪个派生类。什么是Pythonic方式来实现这一点(V3+) 给你: 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

我有一个基类(a)的工厂方法。它需要一个实例来确定实例化哪个派生类。什么是Pythonic方式来实现这一点(V3+)

给你:

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


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

谢谢您的回复,也谢谢您对“cls”的提醒。正如您可能已经猜到的,我对Python比较陌生。关于子类,我没有清楚地说明这个问题。我希望B的构造函数使用A的实例(而不是A的单个属性)。问题是A有很多属性。单独传递它们会增加程序的开销和源代码的视觉污染。有没有办法用a的实例来实例化B?@SmarteePantz为什么a应该知道B?谢谢你的评论。我不想“知道”B,而是希望B构造函数被传递一个A的实例。这个问题在澄清后更有意义吗?
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