python - 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'>
。有人可以解释这里发生了什么吗?
解决方案
如果您查看文档,
返回一个代理对象,它将方法调用委托给
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'>
,而不是int
。int
只是一个变量名。
>>> my_shiny_number = int
>>> my_shiny_number()
0
>>> type(my_shiny_number())
<class 'int'>
相反(请永远不要在实际代码中这样做,这仅用于说明目的):
>>> int = str
>>> int()
''
>>> type(int())
<class 'str'>
推荐阅读
- scheme - 如何在方案中编写一个函数,在带有汽车和 cdr 的列表中找到一个元素?
- c# - 由于 .Net 核心中的 CORS 策略,来自 Angular 的 http 请求被阻止
- javascript - 没有来自窗口的“targetcreated”。在 _blank 中打开文件下载
- python - Keras 密集算法的输入数据形状
- python - 如何为 .NET HTTP 服务器设置 Gitlab CI 并使用 Python 进行测试?
- html - 在 Angular 中使用 PatchValue 或 SetValue 根据更新的 FormControl 更新输入类型时间
- r - 用户在闪亮的应用程序 R 中在数据表中创建新列
- r - Azure 容器 - 简单的 R 管道工部署问题?
- azure-storage - 天蓝色存储帐户中神秘的不可见“blob”文件夹
- google-sheets - 谷歌表格中的 ImportXML 函数以提取特定数据