from typing import TypeVar, Generic
class Beverage: ❶
"""任何饮料"""
class Juice(Beverage):
"""任何果汁"""
class OrangeJuice(Juice):
"""使用巴西橙子制作的美味果汁"""
T = TypeVar('T') ❷
class BeverageDispenser(Generic[T]): ❸
"""一个参数化饮料类型的自动售货机"""
def __init__(self, beverage: T) -> None:
self.beverage = beverage
def dispense(self) -> T:
return self.beverage
def install(dispenser: BeverageDispenser[Juice]) -> None: ❹
"""安装一个果汁自动售货机"""
juice_dispenser = BeverageDispenser(Juice())
install(juice_dispenser)
orange_juice_dispenser = BeverageDispenser(OrangeJuice()) #类型检查会报错,不支持子类
install(orange_juice_dispenser)
orange_juice_dispenser = BeverageDispenser(Beverage()) #类型检查会报错,不支持父类
install(orange_juice_dispenser)
# 修改为
T_co = TypeVar('T_co', covariant=True) ❶#支持协变,支持子类,不支持父类
# T_co = TypeVar('T_co', contravariant=True) # 支持逆变,支持父类,不支持子类
class BeverageDispenser(Generic[T_co]): ❷
def __init__(self, beverage: T_co) -> None:
self.beverage = beverage
def dispense(self) -> T_co:
return self.beverage
def install(dispenser: BeverageDispenser[Juice]) -> None: ❸
"""安装一个果汁自动售货机"""
标签:co,BeverageDispenser,juice,self,dispenser,beverage,协变,泛型
From: https://www.cnblogs.com/weiweivip666/p/17664961.html