类型提示类参数Pylance的几种不同类型

2024-06-28 11:25:06 发布

您现在位置:Python中文网/ 问答频道 /正文

当参数可以包含几个(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]。无论如何,当我尝试时,派伦斯说的是Argument to class must be a base classUnknown type of base class, obscuring deriving type或类似的话

因此,我考虑在第三个文件中创建一个AllowedActions类,它只继承所有可能的动作类。我们的想法是Pathaction=现在将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类似

这让我相信{}我应该分配{},但它似乎有点违背了类型暗示的全部目的

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


Tags: pathself参数hereinitdeftypeaction