当参数可以包含几个(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 class
和Unknown type of base class, obscuring deriving type
或类似的话
因此,我考虑在第三个文件中创建一个AllowedActions
类,它只继承所有可能的动作类。我们的想法是Path
的action=
现在将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类似
这让我相信{
我不知道我是否应该以这种方式解决这个问题,或者也许我认为这一切都是错误的,应该重组继承或其他什么。有什么帮助吗
目前没有回答
相关问题 更多 >
编程相关推荐