問題
假設您有一個類A和一個子類B。如果A該方法foo回傳的變數型別與 不同B,您將如何在不重新定義/覆寫方法本身的情況下覆寫該方法的型別提示?
現實體子
class RGB:
def __init__(self, color: Union[tuple[int, int, int], tuple[int, int, int, int]]) -> None:
self.__color: Union[tuple[int, int, int], tuple[int, int, int, int]] = color
return
def __eq__(self, other: Union[RGB, RGBA]) -> bool:
return isinstance(other, RGB) and self.__color == other.color
@property
def color(self) -> tuple[int, int, int]:
return self.__color
class RGBA(RGB):
def __init__(self, color: tuple[int, int, int, int]) -> None:
super().__init__(color)
return
@property
def color(self) -> tuple[int, int, int, int]:
return self.__color
如您所見,color屬性根據給定顏色是否具有 alpha 值而有所不同。但我不想/不需要重新定義/覆寫color屬性方法,功能不會改變。如何在color不覆寫方法的情況下定義屬性的回傳型別提示?
理想情況下,RGBA該類將只包含該__init__函式。
uj5u.com熱心網友回復:
您可以有一個泛型Color類,作為兩者的共同父級,RGB并由RGBA用于表示每個的元組型別引數化。例如,
from typing import Generic, TypeVar
C = TypeVar('C')
class Color(Generic[C]):
def __init__(self, c: C):
self.__color = c
@property
def color(self) -> C:
return self.__color
class RGB(Color[tuple[int,int,int]]):
pass
class RGBA(Color[tuple[int,int,int,int]]):
pass
這只是一個開始;當您向類添加更多詳細資訊時,您可能會遇到其他問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/417297.html
標籤:
上一篇:當我列印到控制臺時,我的資料框中有一個人在我的資料框中一直顯示為\ufeff
下一篇:有條件的多個表的聯接查詢
