2017-02-02 23 views
1

我正在嘗試定義一個自定義元類型以用於typehinting。例如類型提示的自定義元類型

print(Tuple[int, str, bool]) 
print(CustomType[int, str, bool]) 

第一行很好,很明顯。我將如何實施CustomType,以便它也可以工作?我試過這個:

class CustomType(Tuple): 
    pass 

並得到錯誤TypeError: __main__.CustomType is not a generic class。 我的目標是有元組的專業化與附加類方法

回答

0

據我所知,你可以做到這一點,但內斂的形式,我不認爲你可以指定一個可變數量的參數,而是指定的確切數量的參數。

您需要提供某種類型的變量Tuple當您提供它作爲基類:

from typing import Tuple, TypeVar 
T1, T2, T3 = TypeVar('T1'), TypeVar('T2'), TypeVar('T3') 

class CustomType(Tuple[T1, T2, T3]): 
    pass 

print(CustomType[int, str, bool]) 
# __main__.CustomType[int, str, bool] 

這現在可以連接到它3類型,你需要創建自定義的類型與CustomType(Tuple[T1, T2])2類型,等等。

另外,在Issue 299中增加了對子類別Tuple(和Callable)的支持,並且可用於3.6+