Скажем, я строю граф с узлами и ребрами. У него есть базовый класс Node с общими атрибутами для всех узлов, и каждый конкретный тип узла может наследовать от него, расширяя дополнительные атрибуты.
В качестве примера рассмотрим следующий пример с двумя узлами. типы:
Код: Выделить всё
from typing import TypeVar
# nodes.py
class Node:
def __init__(self, base_param: str) -> None:
self.base_param = base_param
# other base methods...
class NodeType1(Node):
def __init__(self, base_param: str, node_param_type1: int) -> None:
super().__init__(base_param)
self.node_param_type1 = node_param_type1
# other type1 methods...
class NodeType2(Node):
def __init__(self, base_param: str, node_param_type2: int) -> None:
super().__init__(base_param)
self.node_param_type2 = node_param_type2
# other type2 methods...
NodeSubClassType = TypeVar("NodeSubClassType", bound=Node)
Код: Выделить всё
# edges.py
class Edge:
def __init__(self, source: NodeSubClassType, target: NodeSubClassType) -> None:
self.source = source
self.target = target
# other base methods...
class EdgeType1ToType2(Edge):
# Must contain `NodeType1` as `source` and `NodeType2` as `target` when instantiated
pass
# or add other `type1 to type2` methods
Код: Выделить всё
if __name__ == "__main__":
node_type1 = NodeType1("base_param", 1)
node_type2 = NodeType2("base_param", 2)
edge_12 = EdgeType1ToType2(source=node_type1, target=node_type2)
node_type1.base_param # this has no issue
edge_12.source.base_param # this has no issue
node_type1.node_param_type1 # this has no issue
edge_12.source.node_param_type1 # this is not recognized by `mypy` or the LSP
Код: Выделить всё
error: "NodeSubClassType" has no attribute "node_param_type1" [attr-defined]
Found 1 error in 1 file (checked 1 source file)
Я пробовал:
- Добавление лишнего __init__ передача правильных параметров в подкласс, например
но это не работает.
Код: Выделить всё
class EdgeType1ToType2(Edge): def __init__(self, source: NodeType1, target: NodeType2) -> None: super().__init__(source, target)
- и заменим пользовательский тип NodeSubClassType на непосредственно суперкласс Node, но вместо этого я получил то же сообщение с Node.
Подробнее здесь: https://stackoverflow.com/questions/773 ... of-objects