【问题标题】:python: why does `type(super())` return <class 'super'>?python:为什么`type(super())`返回<class 'super'>?
【发布时间】:2021-08-21 04:10:21
【问题描述】:

一个简短的继承示例:

class Person:
    def __init__(self, fname, lname):
        self.firstname = fname
        self.lastname = lname
 
class Student(Person):
    def __init__(self, fname, lname):
        super().__init__(fname, lname) 
        print(type(super()))

现在输入Student("test", "name") 将导致&lt;class 'super'&gt; 被打印到控制台。我不熟悉这种格式。当我执行type(int) 时,我看到类型为type,而不是&lt;class 'int'&gt;。有人可以解释这里发生了什么吗?

【问题讨论】:

  • 试试看type(int())给你什么
  • @bdbd 哦,谢谢。那么这到底是什么意思呢?单独输入 int() 只会返回 0,大概是因为这是默认值。那么为什么type(int()) 不返回int,因为int() 的计算结果是一个int? (int() + 2 工作得很好,所以看起来int() 正在返回一个 int 而不是别的东西)
  • “那么为什么 type(int()) 不返回 int” - 它确实如此。
  • 如前所述,它确实返回int,而int 实际上是class,因此您尝试使用type(int) 打印类定义的类型,以及类实例与type(int()) :)
  • 我也很好奇为什么 type(int) 返回 type 而不是 class,但这里有一些历史记录:stackoverflow.com/questions/4162578/…

标签: python class oop inheritance super


【解决方案1】:

如果你看看docs

返回一个代理对象,该对象将方法调用委托给type 的父类或兄弟类。

这个代理对象的类型是super;假设super_object = super(),那么type(super_object)返回一个类型对象,描述了所有超对象所属的类。就像type(0) 返回一个描述整数的类型对象一样。 &lt;class 'int'&gt; 是这种类型对象的打印方式。有趣的事实:你已经知道这个对象了。

>>> int
<class 'int'>
>>> type(0)
<class 'int'>
>>> type(0) == int
True

请注意,在 Python 中,类的构造函数就是类型对象本身。所以当你写int()时,你正在构造一个int类型的新对象,就像你写Student("test", "name")时,你正在构造一个Student类型的新对象。 super 也是如此:

>>> type(super()) == super
True

为了完善这个答案,我会指出一些非常非常明显的内容,但可能值得在这里提及以防万一。一个变量可能,而且经常,不同于它的值的显示方式。当你说

x = 3
print(x)

您不希望答案是x,而是3,因为这是x 中的值显示自身的方式(通过int.__str__ 方法)。 int 只是另一个变量,恰好包含整数类型对象。此类型对象显示为&lt;class 'int'&gt;,而不是intint 只是一个变量名。

>>> my_shiny_number = int
>>> my_shiny_number()
0
>>> type(my_shiny_number())
<class 'int'>

反之亦然(请永远不要在实际代码中这样做,这仅用于说明目的):

>>> int = str
>>> int()
''
>>> type(int())
<class 'str'>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-03
    • 2013-11-13
    • 1970-01-01
    • 1970-01-01
    • 2011-10-07
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    相关资源
    最近更新 更多