【发布时间】:2020-04-01 08:02:42
【问题描述】:
此代码似乎不起作用:
class Dog:
def __init__(self,color):
assert type(color) == 'str', 'Must be string'
self.color = color
dog = Dog('black')
line 26, in __init__ assert type(color) == 'str', 'Must be string'
AssertionError: Must be string
即使我使用了字符串。他们是一种检查给定参数是否具有正确类型的方法吗?
【问题讨论】:
-
type(color) == str,而不是type(color) == 'str'。另外,请检查isinstance。 -
这能回答你的问题吗? Determine the type of an object?
-
我觉得重要的是要提到这可能是单调的。另外,
assert应该只用于调试。
标签: python