类型提示用于抽象类内部的通用属性

huangapple go评论68阅读模式
英文:

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.)

huangapple
  • 本文由 发表于 2023年1月9日 03:30:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75050688.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定