Python 3 策略/工厂模式:class 的实例类型动态继承一个或多个抽象class 类型的实现
Python 3 Strategy / Factory Pattern: Type for instance of class that dynamically inherits implementations of one or more abstract class types
我正在编写以下 class 结构:
class genericCar(ABC):
baseCarMethodA()
class specificCar(genericCar):
specificCarMethodB()
class genericEngine(ABC):
baseEngineMethodA()
class specificEngine(genericEngine):
specificEngineMethodA()
我想创建一个容器对象,它动态地继承自许多不同的 classes,例如 specificCar 和 specificEngine 等,以构造一个包含它们的方法和字段的对象。
我通过选择对象应通过字符串名称继承的通用 class 类型的实现来做到这一点:
def getBuiltCar(genericCar, genericEngine):
class carFactory(genericCar, genericEngine):
def __init__(self):
pass
return builtCar
想法是构建一个继承自(concreteImplofGenericTypeA、concreteImplofGenericTypeB 等)的对象(汽车)。
我想这样做:
def testDynamicInheritance():
instance = getBuiltCar("specificCar", "specificEngine")
# Type of object instance is a union of specificCar + specificEngine
# but how do I use Type methods to label instance with the proper type?
instance.<autoSuggests>specificEngineMethodA()
instance.<autoSuggests>specificCarMethodB()
Pycharm 自动完成应该识别实例继承自 "specificCar" 和 "specificEngine"。所以这本质上是一个动态混合工厂。
如何使用 Python 的输入系统为 pycharm 提供正确的类型提示,以正确地自动完成动态继承的具体 classes 中的方法和字段?还是我做错了?
您可能想使用更接近 builder creation pattern, or potentially a prototype creation pattern 的东西。
您不是动态多重继承,而是将轮胎、车架、引擎等聚合为组件,并将它们公开为汽车实例。该汽车实例甚至不一定需要子类型。
我正在编写以下 class 结构:
class genericCar(ABC):
baseCarMethodA()
class specificCar(genericCar):
specificCarMethodB()
class genericEngine(ABC):
baseEngineMethodA()
class specificEngine(genericEngine):
specificEngineMethodA()
我想创建一个容器对象,它动态地继承自许多不同的 classes,例如 specificCar 和 specificEngine 等,以构造一个包含它们的方法和字段的对象。
我通过选择对象应通过字符串名称继承的通用 class 类型的实现来做到这一点:
def getBuiltCar(genericCar, genericEngine):
class carFactory(genericCar, genericEngine):
def __init__(self):
pass
return builtCar
想法是构建一个继承自(concreteImplofGenericTypeA、concreteImplofGenericTypeB 等)的对象(汽车)。
我想这样做:
def testDynamicInheritance():
instance = getBuiltCar("specificCar", "specificEngine")
# Type of object instance is a union of specificCar + specificEngine
# but how do I use Type methods to label instance with the proper type?
instance.<autoSuggests>specificEngineMethodA()
instance.<autoSuggests>specificCarMethodB()
Pycharm 自动完成应该识别实例继承自 "specificCar" 和 "specificEngine"。所以这本质上是一个动态混合工厂。
如何使用 Python 的输入系统为 pycharm 提供正确的类型提示,以正确地自动完成动态继承的具体 classes 中的方法和字段?还是我做错了?
您可能想使用更接近 builder creation pattern, or potentially a prototype creation pattern 的东西。
您不是动态多重继承,而是将轮胎、车架、引擎等聚合为组件,并将它们公开为汽车实例。该汽车实例甚至不一定需要子类型。