【问题标题】:Is type the super class of all classes in Python?type 是 Python 中所有类的超类吗?
【发布时间】:2012-08-20 21:30:56
【问题描述】:

鉴于type 是所有类的超类,为什么isinstance(1, type)False? 我对这个概念的理解有误吗?

【问题讨论】:

    标签: python superclass


    【解决方案1】:

    type 不是所有类的超类。它是所有类的类型(没有自定义元类)。注意区别:

    >>> isinstance(1, int)
    True
    >>> isinstance(1, type)
    False
    >>> isinstance(int, type)
    True
    

    数字 1 不是类型的实例。相反,int 类型本身是type 的一个实例。

    编辑:

    这些示例可能对您有所帮助:

    >>> isinstance(1, int)
    True
    >>> issubclass(1, int)
    Traceback (most recent call last):
      File "<pyshell#7>", line 1, in <module>
        issubclass(1, int)
    TypeError: issubclass() arg 1 must be a class
    >>> class Foo(object):
    ...     pass
    >>> isinstance(Foo, type)
    True
    >>> issubclass(Foo, type)
    False # Note the difference from the previous!
    >>> isinstance(Foo, object)
    True
    >>> issubclass(Foo, object)
    True
    >>> isinstance(int, type)
    True
    >>> issubclass(int, type)
    False # Note the difference from the previous!
    

    从您的评论来看,您似乎误解了继承的工作原理。作为类型的实例和作为类型的子类(或子类型)是有区别的。如果对象 X 是类型 A 的 instance,类型 A 是类型 B 的 子类,则 X 也是 B 的实例。但如果类型 A 是instance 类型为 B,则 X 不是 B 的实例。换句话说,子类是可传递的,但实例不是。

    现实世界的类比是“物种”和“智人”之间的类比。您可以说“物种”是一种类型,而“智人”是该类型的一个实例;换句话说,“智人”是一个特定的物种。但是“智人”也是一种类型,一个人就是这种类型的一个实例。例如,巴拉克奥巴马(举一个众所周知的例子)是“智人”的一个例子;也就是说,他是一个特定的智人。但巴拉克奥巴马不是物种的例子。他自己不是一个物种。

    typeint和数字1的关系类似。数字 1 是 int 的实例,inttype 的实例,但这并不意味着 1 是类型的实例。

    【讨论】:

    • 我的意思是当你输入 isinstance(1,int) 时给出 true,当你输入 isinstance(int,type) 时它也给出 true..这意味着 int 是类型的一个实例,而 1 是int.right 的一个实例?这就是我问这个问题的原因。它仍然让我感到困惑。:(
    • @bibeesh:查看我编辑的答案。希望这有助于澄清一点。
    • 感谢您的评论。它对我帮助很大。我忘记了一切都是从对象本身继承的基本规则。
    • @Brenbran:我认为这个答案没有更直接地解释实际上是什么类型:大多数内置类型的元类。而“object”是 O.P. 询问的大多数内置类型的超类
    【解决方案2】:

    那是因为type 不是所有内置类型的超类型。 object 是。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-10
      • 2021-05-01
      • 1970-01-01
      • 2012-11-07
      • 2020-05-24
      • 1970-01-01
      • 1970-01-01
      • 2016-10-26
      相关资源
      最近更新 更多