【问题标题】:Proper way to typecheck object parameter [duplicate]类型检查对象参数的正确方法[重复]
【发布时间】: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


【解决方案1】:

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

您很可能想要检查参数是否是str 的实例:

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

【讨论】:

    【解决方案2】:

    如果你想检查类型,而不使用isinstance,这是你的选择。

    assert type(color) == type(""), 'Must be string'
    

    assert type(color) == str, 'Must be string'
    

    【讨论】:

    • 为什么不只是type(color) == str
    • @Tomerikoo 正确,正在编辑我的答案
    • @Tomerikoo type()isinstance()不是一回事。 (stackoverflow.com/q/1549801/11301900)
    • @AlexanderCécile 我很清楚这一点。我的意思是:考虑到现在的代码是type(color) == type(""),你不妨写type(color) == str。这是否是正确的方法,我没有声称要说明。只是一个明显的修复
    • @Tomerikoo 我很抱歉,不知何故我以为你是这个答案的作者。
    猜你喜欢
    • 2020-07-01
    • 1970-01-01
    • 2020-04-27
    • 2011-12-15
    • 1970-01-01
    • 2015-09-09
    • 2021-06-24
    • 2010-10-18
    相关资源
    最近更新 更多