【发布时间】:2021-06-15 08:36:23
【问题描述】:
如何使用类型提示指定多个类?
为了更清楚,我举个例子。我有一个名为 weight 的函数,它获取一个对象作为参数并返回其权重(私有属性)。但是,我只想称量土豆和洋葱,而不是西红柿,通过使用注释,如果我尝试称量西红柿,应该会收到警告。
这里有一些代码:
class Potato:
def __init__(self, weight: float):
self.__weight = weight
@property
def weight(self) -> float:
return self.__weight
class Onion:
def __init__(self, weight: float):
self.__weight = weight
@property
def weight(self) -> float:
return self.__weight
class Tomato:
def __init__(self, weight: float):
self.__weight = weight
@property
def weight(self) -> float:
return self.__weight
def weigh(object_: annotation) -> float:
# here there should be an annotation for classes Potato and Onion
return object_.weight
p = Potato(402.9)
o = Onion(199)
t = Tomato(155.6)
print(weigh(p))
print(weigh(o))
print(weigh(t)) # this shouldn't be possible
【问题讨论】:
-
你可以使用
Union[Potato, Onion] -
你所做的似乎是故意反对 OOP。你可以用重量来衡量任何东西,你甚至可以拥有一个 Weighable 抽象基类。
-
我同意@jonrsharpe,创建一个具有
weigh函数的Weighable基类。 Python 并没有真正的私有属性或类型要求。只有约定
标签: python class oop annotations type-hinting