【问题标题】:Why use isinstance() instead of type()? [duplicate]为什么使用 isinstance() 而不是 type()? [复制]
【发布时间】:2015-07-14 23:26:39
【问题描述】:

我看到人们经常推荐使用 isinstance() 而不是 type(),我觉得这很奇怪,因为 type() 对我来说似乎更具可读性。

>>> isinstance("String",str)
True
>>> type("String") is str
True

后者看起来更 Pythonic 和清晰,而前者有点模糊,暗示了我的特定用途(例如,测试用户构建的类而不是内置类型),但还有其他一些我不知道的好处吗? type() 是否会导致一些不稳定的行为或错过一些比较?

【问题讨论】:

  • 我记得文档已经解释了为什么它应该使用isinstance。我需要时间去找。
  • polymorphish 是一个关键字,如果您想了解更多信息,请查找。
  • 请注意,最 Pythonic 的方法是将其视为是字符串(或更一般的东西,例如序列),并且(可选)从错误中恢复不是。我偶尔会使用isinstance(whatever, basestr) 我需要将字符串与其他序列区别对待,但除此之外有什么关系吗?

标签: python types


【解决方案1】:

让我举一个简单的例子,为什么它们可以不同:

>>> class A(object): pass
>>> class B(A) : pass
>>> a = A()
>>> b = B()

到目前为止,声明了一个变量A 和一个派生自A 的变量B。

>>> isinstance(a, A)
True
>>> type(a) == A
True

但是

>>> isinstance(b, A)
True
>>> type(b) == A
False

【讨论】:

    【解决方案2】:

    您排除了在此处使用子类的可能性。

    当子类满足接口时,为什么要限制自己只使用一种类型?如果有人想使用class mystr(str): ... 做某事,您的代码仍然可以工作,并且不需要知道使用了子类。

    因此,使用isinstance() 是更 Pythonic 的方法;你的代码应该寻找支持的行为,而不是特定的类型。

    【讨论】:

      【解决方案3】:

      Python 2.x 的基本示例:标准字符串和 unicode 字符串,具有通用基类 basestring:

      s = "123"
      u = u"123"
      isinstance(s, str) is True
      type(u) == str  # something which has string nature returns False for this test
      # these tests are common-pattern in Python 2.x and behaves correctly
      isinstance(s, basestring) is True
      isinstance(u, basestring) is True
      

      【讨论】:

        【解决方案4】:

        下面是反例:

        class A():
            pass
        
        a = A()
        
        >>> isinstance(a, A)
        True
        >>> type(a) is A
        False
        

        因此,我认为isinstance 是一个更通用的。

        【讨论】:

        • 请注意,这仅在A 是旧式类时才会发生;具有新样式的类(3.x 中的所有类,2.x 中从 object 继承的类)type(a) is A。
        猜你喜欢
        • 2018-11-03
        • 1970-01-01
        • 2020-11-14
        • 2011-10-03
        • 1970-01-01
        • 2013-04-16
        相关资源
        最近更新 更多