你应该isinstance
在这里使用而不是type
:
def distance_from_zero(d):
if isinstance(d, (int, float)):
return abs(d)
else:
return "Not an integer or float!"
iftype(d) == int or float
总是会True
像它被评估的那样float
,它是一个True
值:
>>> bool(float)
True
帮助isinstance
:
>>> print isinstance.__doc__
isinstance(object, class-or-type-or-tuple) -> bool
Return whether an object is an instance of a class or of a subclass thereof.
With a type as second argument, return whether that is the object's type.
The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
isinstance(x, A) or isinstance(x, B) or ... (etc.).
相关:如何在 Python 中比较对象的类型?