英文:
type hint for generic attribute inside abstract class
问题
我有一个关于类型的复杂问题,我无法解决。
假设我有一些抽象类和一个等效于以下内容的泛型类型
from abc import ABC
from typing import Generic, TypeVar
class Action(ABC):
pass
ActionTypeVar = TypeVar("ActionTypeVar", bound="Action")
class Agent(ABC, Generic[ActionTypeVar]):
actions: tuple[ActionTypeVar, ...]
def get_action() -> ActionTypeVar:
return self.actions[0]
这个代码按预期工作。但是我需要在类外定义一个类似于get_action
的函数(实际上是在不同的包中)。
def get_action_outside_class(agent: Agent) -> ActionTypeVar:
return agent.actions[0]
问题在于这里返回类型不再精确,因为我们已经超出了类的范围。我想指示这个返回类型与agent.actions
的元素类型相同。
我尝试在get_action
的返回中引用Agent.actions
的元素,但是我找不到合适的方法来实现它。
英文:
I have a convoluted problem with types that I can´t solve.
Let's say I have some abstract classes and a generic type equivalent to this
from abc import ABC
from typing import Generic, TypeVar
class Action(ABC):
pass
ActionTypeVar = TypeVar("ActionTypeVar", bound="Action")
class Agent(ABC, Generic[ActionTypeVar]):
actions: tuple[ActionTypeVar, ...]
def get_action() -> ActionTypeVar:
return self.action[0]
This works as intended. But I need is to define a function similar to get_action outside the class(in a different package in fact).
def get_action_outside_class(agent: Agent) -> ActionTypeVar:
return agent.actions[0]
The problem is that here the return type is not precise anymore, since we are outside the scope of the class. I wanted to indicate this is of the same type as the elements of agent.actions
.
I have tried referencing the elements of Agent.actions
in the return of get_action
but I can't find out a proper way to do it.
答案1
得分: 1
你没有通用地使用 Agent
。
def get_action_outside_class(agent: Agent[ActionTypeVar]) -> ActionTypeVar:
return agent.actions[0]
(任何 TypeVar
都可以;它不需要与您在定义 Agent
时使用的相同。)
英文:
You aren't using Agent
generically.
def get_action_outside_class(agent: Agent[ActionTypeVar]) -> ActionTypeVar:
return agent.actions[0]
(Any TypeVar
would do; it doesn't need to be the same one you used when defining Agent
.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论