0

当参数可以采用多个(15+)个不同的类时,输入提示的最佳方式是什么?

我有一个Path带有参数的类action,可以采取许多不同类型的动作。每个动作都派生自一个基类Action,并实现了该子类与其兄弟类相比特定的东西:

# path.py
class Path:
    def __init__(self, action)       # action: Any? Union[A,B,C,...]?
        # do some init stuff here
        
# actions.py
class Action:
    def __init__(self, ...)
        # do some init stuff here

class ActionA(Action):
    def __init__(self, ...)
        # do some init stuff here

class ActionB(Action):
    def __init__(self)
        # do some init stuff here


# plenty more Action subclasses
# in fact, in the future the list will probably keep growing
...

那里的大多数答案只是提到Union,但这仅适用于几种可能的类型。我不认为我应该在像actions: Union[ClassA, ClassB, ClassC, ..., ClassZ]. 无论如何,当我尝试时,Pylance 说的是Argument to class must be a base classUnknown type of base class, obscuring deriving type或类似的。

所以我想AllowedActions在第三个文件中创建一个类,它只是继承自所有可能的动作类。这个想法是让Path'saction=现在AllowedAction成为一个包罗万象的:

class AllowedAction(ActionA, ActionB, ActionC, ..., ActionZ):
    def __init__(self):
        pass

我不介意在Action这个AllowedAction声明中添加子类,Path我只能说action: AllowedAction. 但是,现在当我实例化Path并向它的action参数添加一些东西时Path(action=ActionA()),我得到了Argument of type "ActionA" cannot be assigned to parameter "action" of type "AllowedAction". 显然是因为子类ActionA与 catch-all / subchild 类不同AllowedAction,而是像 wth。

这让我相信PathI should just assign action: Any,但它似乎首先违背了类型提示的整个目的?

我不知道我是否应该以这种方式解决问题,或者我认为这一切都错了,应该重组继承或其他东西。有什么帮助吗?

4

0 回答 0