简体   繁体   English

如何调用父类的__repr__?

[英]How to invoke __repr__ of parent class?

So the situation I want to resolve is pretty simple.所以我想解决的情况很简单。 Say I have a subclass C that extends parents B and A .假设我有一个扩展父类BA的子类C Parents B , and A each have their own __repr__ methods.父母BA都有自己的__repr__方法。 When I print C , the __repr__ method of parent A is always invoked, but I want to invoke parent B 's.当我打印C ,总是调用父A__repr__方法,但我想调用父B的方法。

How can I do this?我怎样才能做到这一点?

Assume A is defined like this:假设A定义如下:

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

and B is defined similarly: B的定义类似:

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

while C is defined like so:C是这样定义的:

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

or something similar.或类似的东西。 print A() will yield This is A , while the same for B will yield This is B . print A()将产生This is A ,而同样的B将产生This is B print C() will, as you describe, give This is A .正如您所描述的, print C()将给出This is A However, if you just change the order of C 's inheritance:但是,如果您只是更改C的继承顺序:

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

then print C() will give you This is B .然后print C()会给你This is B Simple as that.就那么简单。

If all I wanted was to call an inherited class's repr I would just do:如果我只想调用继承类的代表,我会这样做:

class C(B, A): # whatever order
    def __repr__(self):
        return A.__repr__(self)

I had a case similar, but slightly different to this question.我有一个类似的案例,但与这个问题略有不同。 I wanted to print the default repr of an inherited class.我想打印继承类的默认代表。 For me class C was dynamically defined with B being a mixin class, but I wanted to show the name and module of the "main" class A. I ended up with this solution.对我来说, C类是动态定义的, B是一个混合类,但我想显示“主”类 A 的名称和模块。我最终得到了这个解决方案。

class C(B, A):
    def __repr__(self):
        '''Override repr to show the name and path of the main cls.'''
        return '<{} {}.{} object at {}>'.format(
            self.__class__.__name__,
            A.__module__,
            A.__name__,
            hex(id(self)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM