【问题标题】:Python 3 inheritance multiple classes with __str__Python 3 使用 __str__ 继承多个类
【发布时间】:2019-03-30 09:46:18
【问题描述】:
如何使用其他类的多个__str__?例如:
class A:
def __str__(self):
return "this"
class B:
def __str__(self):
return "that"
class C(A,B):
def __str__(self):
return super(C, self).__str__() + " those"
# return something(A) + " " something(B) + " those"
cc = C()
print(cc)
输出:这些
我希望输出是:那些
这个post 几乎是一个解决方案(带有super())
【问题讨论】:
标签:
python
string
python-3.x
class
inheritance
【解决方案1】:
我尝试将此代码示例添加到 blue_note 答案,但他将更改还原为答案。
直接super() 调用在多重继承中不太适用。它会在第一个找到的__str__ 方法处停止。相反,您可以通过迭代 __bases__ 来调用所有父 __str__ 方法。请记住,这也将返回 object 类型。可能需要也可能不需要。
例子:
def __str__(self) -> str:
bstr = ""
for base in type(self).__bases__:
bstr += base.__str__(self) if base.__name__ != 'object' else ""
return bstr
【解决方案2】:
对于多重继承,super() 从左到右搜索具有该属性的 first 类。因此,它将停在A。您可以使用特殊的 __bases__ 属性访问所有父类,并循环访问它们,在每个父类上调用 str。
【解决方案3】:
显式调用父类__str__方法:
class C(A, B):
def __str__(self):
return A.__str__(self) + ' ' + B.__str__(self) + ' those'
# or return '{} {} those'.format(A.__str__(self), B.__str__(self))