如何连接Object字符串(原始)而不重载和显式类型cast(str())?
class Foo:
def __init__(self, text):
self.text = text
def __str__(self):
return self.text
_string = Foo('text') + 'string'
Run Code Online (Sandbox Code Playgroud)
输出:
Traceback (most recent call last):
File "test.py", line 10, in <module>
_string = Foo('text') + 'string'
TypeError: unsupported operand type(s) for +: 'type' and 'str'
Run Code Online (Sandbox Code Playgroud)
运营商+必须超载?还有其他方式(只是想知道)?
PS:我知道重载运算符和类型转换(如str(Foo('text')))
Sve*_*ach 15
只需定义__add__()和__radd__()方法:
class Foo:
def __init__(self, text):
self.text = text
def __str__(self):
return self.text
def __add__(self, other):
return str(self) + other
def __radd__(self, other):
return other + str(self)
Run Code Online (Sandbox Code Playgroud)
它们将根据您是Foo("b") + "a"(呼叫__add__())还是"a" + Foo("b")(呼叫__radd__())来呼叫.
_string = Foo('text') + 'string'
Run Code Online (Sandbox Code Playgroud)
这一行的问题在于 Python 认为您想将 a 添加string到类型为 的对象Foo,而不是相反。
如果你写的话,它会起作用:
_string = "%s%s" % (Foo('text'), 'string')
Run Code Online (Sandbox Code Playgroud)
编辑
你可以试试
_string = 'string' + Foo('text')
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您的Foo对象应该自动转换为字符串。