【问题标题】:Specifying multiple classes with type hinting [duplicate]使用类型提示指定多个类[重复]
【发布时间】: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


【解决方案1】:

你可以使用:

from typing import Union    
def weigh(object_: Union[Potato, Onion]) -> float:
    return object_.weight
t = Tomato(155.6)
print(weigh(t))

标记为

Argument 1 to "weigh" has incompatible type "Tomato"; expected "Union[Potato, Onion]"

【讨论】:

    猜你喜欢
    • 2016-02-29
    • 2020-03-30
    • 2018-07-20
    • 2023-03-29
    • 2011-04-19
    • 2014-09-11
    • 2022-07-28
    • 2021-04-06
    相关资源
    最近更新 更多