python - 如何调用父类的__repr__?

标签 python

所以我要解决的情况很简单。假设我有一个扩展父类 BA 的子类 C。父级 BA 每个都有自己的 __repr__ 方法。当我打印 C 时,总是调用父 A__repr__ 方法,但我想调用父 B的。

我该怎么做?

最佳答案

假设 A 定义如下:

class A():
    def __repr__(self):
        return "This is A"

B的定义类似:

class B():
    def __repr__(self):
        return "This is B"

虽然 C 是这样定义的:

class C(A, B):
    def __init__(self):
        pass

或类似的东西。 print(A()) 将输出 This is A,而 B() 将输出 This is B。如您所述,print(C()) 将给出 This is A。但是,如果您只是更改 C 的继承顺序:

class C(B, A): # change order of A and B
    def __init__(self):
        pass

然后 print(C()) 会给你 This is B。就这么简单。

关于python - 如何调用父类的__repr__?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24978530/

相关文章:

python - 如何使用正则表达式合并数据帧的多列?

python - scapy 中嗅探功能的过滤器无法正常工作

python - Django 和 scikit-image 请求超时

python - 使用 Strptime 时出现 ValueError

python - python套接字编程: error trying to connect to server

python - 通过树莓派同时播放多个声音文件,最好使用python

python - 如何在 Keras 2.0 中使用 "Merge"顺序模型?

python - 查找列表列表中n个列表中出现的元素

python - pandas 数据框中相应行之间的日期之间的差异

python - Flask 请求将 pandas 传递给_json 与 curl 或 Postman