首页 > 解决方案 > 类型检查对象参数的正确方法

问题描述

此代码似乎不起作用:

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

即使我使用了字符串。他们是一种检查给定参数是否具有正确类型的方法吗?

标签: python

解决方案


首先,'str'str不同的是:第一个是字符串,第二个是str类。如果与班级相比,(type('hello') == str) is True.

您很可能想检查参数是否是以下实例str

assert isinstance(color, str), 'Must be string'

推荐阅读