首页 > 解决方案 > 如何检查变量是浮点数还是整数?

问题描述

例如,当我__init__()在 Car 类中构造 a 时,我想检查变量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__()无法正常工作。我如何解决它?

标签: pythonclasserror-handling

解决方案


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

您还使用current_gas_levelcurrent_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

为了使定义更容易理解,我可能还建议使用数据类和 a__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")

推荐阅读