如何检查变量是浮点数还是整数?

时间:2021-05-04 17:02:53

标签: python class error-handling

当我在 Car 类中构造 function myFunction() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var s = ss.getActiveSheet(); var c1 = s.getRange("B2"); var c2 = s.getRange("A2") var fldr = DriveApp.getFolderById("14ZKphLE02f6tdyU7LGEjbEEfrfD89nJM"); var files = fldr.getFiles(); var urls = [], f, str; while (files.hasNext()) { f = files.next(); str = '=hyperlink("' + f.getUrl() + '")'; urls.push([str]); } s.getRange(c1.getRow(), c1.getColumn(), urls.length).setFormulas(urls); var ids = [], f, str; while (files.hasNext()) { f = files.next(); str = 'f.getName()'; ids.push([str]) } s.getRange(c2.getRow(), c2.getColumn(), ids.length).setValues(ids); } 时,比如说,我想检查变量 __init__()make 分别是字符串和浮点数还是整数(非负数)。

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

我试过了

current_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") 无法正常工作。我该如何解决?

1 个答案:

答案 0 :(得分:4)

看起来您在第二个 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")
相关问题