我想要解决的情况非常简单。假设我有一个子类
如何实现呢?
C
,它继承了父类B
和A
。父类B
和A
都有自己的__repr__
方法。当我打印C
时,总是调用父类A
的__repr__
方法,但我想调用父类B
的__repr__
方法。如何实现呢?
C
,它继承了父类B
和A
。父类B
和A
都有自己的__repr__
方法。当我打印C
时,总是调用父类A
的__repr__
方法,但我想调用父类B
的__repr__
方法。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
。就这么简单。
class C(B, A): # whatever order
def __repr__(self):
return A.__repr__(self)
我有一个类似但略有不同于这个问题的案例。我想要打印继承类的默认repr。对我来说,类C
是动态定义的,其中B
是一个mixin类,但我想显示“主”类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)))