![](/img/trans.png)
[英]How to use a class attribute as the type hint for a method inside the class?
[英]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.action[0]
這按預期工作。 但我需要的是在類外定義一個類似於 get_action 的 function(實際上是在不同的 package 中)。
def get_action_outside_class(agent: Agent) -> ActionTypeVar:
return agent.actions[0]
問題是這里的返回類型不再精確,因為我們在 class 的 scope 之外。我想表明這與agent.actions
的元素屬於同一類型。
我曾嘗試在Agent.actions
的返回中引用get_action
的元素,但我找不到合適的方法來做到這一點。
您一般不會使用Agent
。
def get_action_outside_class(agent: Agent[ActionTypeVar]) -> ActionTypeVar:
return agent.actions[0]
(任何TypeVar
都可以;它不需要與您在定義Agent
時使用的相同。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.