小编tja*_*son的帖子

为什么str(super(B,b))不等于super(B,b).__ str __()?

它应该遵循str(super(B, b)) == super(B, b).__str__(),但事实并非如此(交互式版本):

class A:
    def __str__(self):
        return "A"


class B(A):
    def __str__(self):
        return "B"


b = B()   
b_super = super(B, b) 
print(str(b_super))       # "<super: <class 'B'>, <B object>>"
print(b_super.__str__())  # "A"
Run Code Online (Sandbox Code Playgroud)

那我哪里出错了?超级机制不适用于魔术方法吗?难道str不能调用__str__在这种情况下?它与本段有关:

请注意,它super()是作为显式点状属性查找的绑定过程的一部分实现的,例如super().__getitem__(name).它通过实现自己的__getattribute__()方法以可预测的顺序搜索类来支持协作多重继承.因此,super()对于使用语句或运算符(例如)的隐式查找,未定义super()[name].

python inheritance python-3.x

24
推荐指数
1
解决办法
821
查看次数

标签 统计

inheritance ×1

python ×1

python-3.x ×1