我有這樣的事情:from typing import TypeVar, Generic, TupleT = TypeVar('T')S = TypeVar('S')U = TypeVar('U')class Foo(Generic[T, S]): def get_type_vars(self) -> Tuple[TypeVar]: return #TODO how do I return T and S here?assert Foo().get_type_vars() == (T, S)有什么辦法可以得到這種行為嗎?我需要一種方法來找出 和S是T通用 Class 的 TypeVars Foo。有任何想法嗎?我應該提到,我編寫了一些類裝飾器,并且該方法get_type_vars()將由裝飾器添加到類中。self所以我所擁有的只是方法中的實例:def get_type_vars(self) -> Tuple[TypeVar]: return #TODO how do I return T and S here in case that self is an instance of Foo?
1 回答

寶慕林4294392
TA貢獻2021條經驗 獲得超8個贊
您可以get_args結合使用來__orig_bases__檢查基類的泛型類型:
class Foo(Generic[T, S]):
def get_type_vars(self) -> Tuple[TypeVar]:
return get_args(type(self).__orig_bases__[0])
不過,對于更復雜的繼承鏈來說,這會變得更復雜一些。
添加回答
舉報
0/150
提交
取消