【发布时间】:2021-05-04 17:02:53
【问题描述】:
例如,当我在 Car 类中构造 __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")
但是,这个__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