python - 如何检查变量是浮点数还是整数?
问题描述
例如,当我__init__()
在 Car 类中构造 a 时,我想检查变量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")
但是,这__init__()
无法正常工作。我如何解决它?
解决方案
看起来您在第二个 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
为了使定义更容易理解,我可能还建议使用数据类和 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")
推荐阅读
- python - 在 Cython cdef 类中定义自定义类
- r - R中时间序列数据的增长率
- javascript - Axios 在创建时返回 405 错误(Laravel+Vue)
- python-3.x - requests_oauthlib 是否默认缓存,我什至应该缓存吗?
- python - 计算文本文件中列表中字符串的出现次数
- sql-server - 使用 LINQ-to-SQL 将 ASP.NET Web 窗体应用程序迁移到 SQL Server 2016 后的性能问题
- c# - 两支数据流网络不完整
- python - 数字签名验证失败
- python - PyPy 找不到包
- amazon-web-services - aws cloudwatch 日志过滤器模式包括匹配模式之前和/或之后的行