【问题标题】:How to check if a variable is float or int?如何检查变量是浮点数还是整数?
【发布时间】:2021-05-04 17:02:53
【问题描述】:

例如,当我在 Car 类中构造 __init__() 时,我想检查变量 makecurrent_gas 分别是字符串和浮点数或整数(非负数)。

那么我如何为每个变量引发适当的错误呢?

我试过了

class Car:
    def __init__(self,make,current_gas):
        if type(make) != str:
            raise TypeError("Make should be a string")
        if not type(current_gas) == float or type(current_gas) == int:
            raise TypeError("gas amount should be float or int")
        if current_gas <=0:
            raise ValueError("gas amount should not be negative")

但是,这个__init__() 不能正常工作。我该如何解决?

【问题讨论】:

  • “无法正常工作”是什么意思?确切的行为是什么?
  • 这能回答你的问题吗? How to determine a Python variable's type?
  • 请注意,在 not ... or ... 中,not 仅适用于第一个布尔值,而不适用于整个分支
  • 显示错误信息。另请注意,您使用了current_gas_level,似乎没有在任何地方定义。
  • first_car=Car('Toyota','Corolla',20)gas amount should be float or int

标签: python class error-handling


【解决方案1】:

看起来你在第二个 if 语句上的布尔逻辑是错误的(not 需要围绕这两个检查),但是,你可以使用isinstance 来简化对多个类型的检查。

您还使用了current_gas_level 而不是current_gas。试试这样的:

class Car:
    def __init__(self, make, current_gas):
        if not isinstance(make, str):
            raise TypeError("Make should be a string")
        if not isinstance(current_gas, (int, float)):
            raise TypeError("gas amount should be float or int")
        if current_gas <= 0:
            raise ValueError("gas amount should not be negative")

        self.make = make
        self.current_gas = current_gas

为了使定义更容易理解,我还建议使用数据类和__post_init__ 进行验证。

from dataclasses import dataclass
from typing import Union


@dataclass
class Car:
    make: str
    current_gas: Union[int, float]

    def __post_init__(self):
        if not isinstance(self.make, str):
            raise TypeError("Make should be a string")
        if not isinstance(self.current_gas, (int, float)):
            raise TypeError("gas amount should be float or int")
        if self.current_gas <= 0:
            raise ValueError("gas amount should not be negative")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-22
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    • 2022-01-10
    • 2012-08-19
    相关资源
    最近更新 更多