【问题标题】:Is object a subclass of type in Python 2.X?对象是 Python 2.X 中类型的子类吗?
【发布时间】:2019-03-18 20:57:39
【问题描述】:

我从 Learning Python(第 5 版)中读到(第 1364 页,第 40 章):

在 Python 2.X 中,新式类继承自 object,它是 type 的子类;经典类是 type 的实例,不是从类创建的。

然而,

issubclass(object, type)

给我

False

在 Python 2.7 中。

所以,作者似乎做了一个错误的陈述,即 objecttype 的子类,还是我遗漏了什么?

【问题讨论】:

  • 如果你尝试issubclass(type(object), type)会怎样?
  • "classic classes are instances of type" 也是假的。

标签: python python-2.7 inheritance subclass metaclass


【解决方案1】:

object 不是type 的子类,这将使其成为metaclass。而objecttype 类型的instance

函数issubclass 检查给定类是否继承自另一个。

class A:
    pass

class B(A):
    pass

print(issubclass(B, A)) # True

它不检查给定类型的实例 os。要验证object 是否确实属于type,您需要使用isinstance

print(isinstance(object, type)) # True

【讨论】:

    【解决方案2】:

    使用isinstance()。在python 2.7.10

    print object
    print isinstance(object, type)
    print issubclass(object, type)
    print object.__class__
    

    输出

    <type 'object'>
    True
    False
    <type 'type'>
    

    type 是一个元类explained here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-06
      • 2016-10-19
      • 1970-01-01
      • 2011-02-14
      • 2015-01-08
      • 1970-01-01
      • 2019-02-25
      • 1970-01-01
      相关资源
      最近更新 更多