python - 类型检查对象参数的正确方法
问题描述
此代码似乎不起作用:
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
即使我使用了字符串。他们是一种检查给定参数是否具有正确类型的方法吗?
解决方案
首先,'str'
和str
不同的是:第一个是字符串,第二个是str
类。如果与班级相比,(type('hello') == str) is True
.
您很可能想检查参数是否是以下实例str
:
assert isinstance(color, str), 'Must be string'
推荐阅读
- dialogflow-es - 昨天有效的操作现在确实崩溃了
- c - 我怎样才能使新结构与旧结构兼容?
- c# - Serilog 的显式日志级别而不是 MinimumLevel
- python - 如何用opencv正确叠加两个图像
- r - 使用 set.seed 命令的不同样本结果?
- java - 是否有 INDArray 的方法来执行两个 INDArray(具有不同大小)的相加?
- database - 在 node-oracledb 中使用事务
- c# - 无法从 c# 代码调用类模板的非虚拟函数
- ruby-on-rails - form_for 'file_field' 未显示在编辑操作中选择的文件
- javascript - Element 的 Microsoft Edge 实例返回的结果与 chrome/firefox 不同