?,python,class,oop,inheritance,super"/>

首页 > 解决方案 > python:为什么`type(super())`返回?

问题描述

一个简短的继承示例:

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")将导致<class 'super'>打印到控制台。我不熟悉这种格式。当我这样做时,type(int)我将类型视为type,而不是<class 'int'>。有人可以解释这里发生了什么吗?

标签: pythonclassoopinheritancesuper

解决方案


如果您查看文档

返回一个代理对象,它将方法调用委托给type.

此代理对象的类型为super; 假设super_object = super(),则type(super_object)返回一个类型对象,该对象描述了所有超对象所属的类。就像type(0)返回一个描述整数的类型对象一样。<class 'int'>是这种类型的对象如何打印自己。有趣的事实:你已经知道这个对象。

>>> 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只是另一个变量,恰好包含整数类型对象。此类型对象将自身显示为<class 'int'>,而不是intint只是一个变量名。

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

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

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

推荐阅读