python:type(super())`return<;类别';超级'>;?

python:type(super())`return<;类别';超级'>;?,python,class,oop,inheritance,super,Python,Class,Oop,Inheritance,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(supe

一个简短的继承示例:

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”)
将导致
打印到控制台。我不熟悉这种格式。当我执行
type(int)
时,我看到的类型是
type
,而不是
。有人能解释一下这里发生了什么吗?

如果你看看

返回一个代理对象,该对象将方法调用委托给
类型的父类或同级类

此代理对象的类型为
super
;假设
super\u object=super()
,则
type(super\u object)
返回一个类型对象,该对象描述所有超级对象所属的类。就像
type(0)
一样,返回一个描述整数的类型对象<代码>是此类型对象打印自身的方式。有趣的事实:你已经知道这个物体了

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

为了总结这个答案,我会注意到一些非常非常明显的东西,但可能值得一提,以防万一。一个变量可能,而且经常与它的值的显示方式不同。当你说

x = 3
print(x)
您不希望答案是
x
,而是
3
,因为
x
中的值是通过
int.\uuu str\uu
方法显示的
int
只是另一个变量,恰好包含integer类型的对象。此类型对象本身显示为
,而不是
int
int
只是一个变量名

>>> my_shiny_number = int
>>> my_shiny_number()
0
>>> type(my_shiny_number())
<class 'int'>
>>我的\u闪亮\u编号=int
>>>我的号码()
0
>>>键入(我的号码())
相反(请永远不要在实际代码中这样做,这只是为了说明):

>>int=str
>>>int()
''
>>>类型(int())

尝试查看
类型(int())
给出了什么you@bdbd噢,谢谢。那么这到底意味着什么呢?输入
int()
本身只返回0,可能是因为这是默认值。那么为什么
type(int())
不返回
int
,因为
int()
的计算结果是int?(
int(),因此,您试图用
type(int)
打印类定义的类型,用
type(int())
打印类实例:)我也很好奇为什么
type(int)
返回
type
,而不是
class
,但这里有一些历史留给我们:
>>> my_shiny_number = int
>>> my_shiny_number()
0
>>> type(my_shiny_number())
<class 'int'>
>>> int = str
>>> int()
''
>>> type(int())
<class 'str'>