python - super().__repr__() 和 repr(super()) 有什么区别?

标签 python python-3.x class super repr

在 python (3.5.2) 中,我期望 repr(obj) 函数调用 obj 的魔法方法 __repr__() > 的类(class)。 但是,同时调用它们似乎不会产生相同的结果。谁能解释为什么?

示例代码:

class parent:

    def __init__(self):
        self.a = "haha"

    def __repr__(self):
        return repr(self.a)

class child(parent):
    def __init__(self):
        super().__init__()
        self.b="bebe"

    def __repr__(self):
        return "("+super().__repr__()+", "+repr(super())+", "+self.b+")"

    def print1(self):
        print("super().__repr__() returns:", super().__repr__())
        print("repr(super()) returns:", repr(super()))
        print("plom(super()).__repr__() returns:", plom(super()).__repr__())
        print("repr(plom(super())) returns:", repr(plom(super())))

def plom(var):
    return var

t=child()
print(t.__repr__())
print(repr(t))
print('-----')
t.print1()
print('-----')
print(plom(t).__repr__())
print(repr(plom(t)))

结果:

>>> 
 RESTART: test super.py 
('haha', <super: <class 'child'>, <child object>>, bebe)
('haha', <super: <class 'child'>, <child object>>, bebe)
-----
super().__repr__() returns: 'haha'
repr(super()) returns: <super: <class 'child'>, <child object>>
plom(super()).__repr__() returns: 'haha'
repr(plom(super())) returns: <super: <class 'child'>, <child object>>
-----
('haha', <super: <class 'child'>, <child object>>, bebe)
('haha', <super: <class 'child'>, <child object>>, bebe)
>>> 

最佳答案

调用 repr(super()) 直接访问 super 上的 __repr__(技术上, C PyTypeObject 结构的 tp_repr 定义了 super 类型)。大多数特殊的 dunder 方法在隐式调用时都会以这种方式运行(而不是将它们显式调用为方法)。 repr(x) 不等同于 x.__repr__()。你可以认为 repr 被定义为:

def repr(obj):
    return type(obj).__repr__(obj)  # Call unbound function of class with instance as arg

当你期待它时:

def repr(obj):
    return obj.__repr__()  # Call bound method of instance

这种行为是故意的;第一,为每个实例定制 dunder 方法没有什么意义,第二,禁止它允许在 C 级别编写更高效的代码(它有更快的方法来完成上面的说明性方法所做的事情)。

相比之下,super().__repr__() 查找super 实例 上的方法,并且super 定义了一个自定义的 tp_getattro(大致相当于定义一个自定义的 __getattribute__ 方法),这意味着对实例的查找在找到 tp_repr 之前被拦截>/__repr__,而是通过自定义属性 getter(执行父类(super class)委托(delegate))进行分派(dispatch)。

关于python - super().__repr__() 和 repr(super()) 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53454458/

相关文章:

python - with()语句从opencv中的VideoCapture读取?

python - 什么是 `--context` 的 Kubernetes API 等价物?

VB.NET、类和模块与函数

python - 如何取消除 argmax 之外的所有条目?

python - 如何通过单击按钮重新执行我的 Python 程序

Python - Pandas - 计算字符串中字符出现的次数并替换字符串值

python - 如何将所有 .csv 和 .xlsx 文件名与最少一个字符相匹配?

python - 调试 urwid 应用程序的好选择是什么?

java - 关于 Java 泛型

python - 如何使用 __init__ 缩短这段代码?