如何将“Object”与字符串连接?
如何在不重载和显式类型转换 (str()
) 的情况下将 Object
与字符串(原始)连接?
class Foo:
def __init__(self, text):
self.text = text
def __str__(self):
return self.text
_string = Foo('text') + 'string'
输出:
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'
运算符+
必须重载吗? 还有其他方法吗(只是想知道)?
PS:我知道重载运算符和类型转换(例如 str(Foo('text'))
)
How to concatenate Object
with a string (primitive) without overloading and explicit type cast (str()
)?
class Foo:
def __init__(self, text):
self.text = text
def __str__(self):
return self.text
_string = Foo('text') + 'string'
Output:
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'
operator +
must be overloaded?
Is there other ways (just wondering)?
PS: I know about overloading operators and type casting (like str(Foo('text'))
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需定义
__add__()
和__radd__()
方法:它们将根据您是否执行
Foo("b") + "a"(调用
__add__()
)或"a" + Foo("b")
(调用__radd__()
)。Just define the
__add__()
and__radd__()
methods:They will be called depending on whether you do
Foo("b") + "a"
(calls__add__()
) or"a" + Foo("b")
(calls__radd__()
).这行代码的问题在于,Python 认为您想要将
string
添加到Foo
类型的对象,而不是相反。如果你写:
EDIT
你可以尝试一下,
在这种情况下,你的
Foo
对象应该自动转换为字符串。The problem with this line is that Python thinks you want to add a
string
to an object of typeFoo
, not the other way around.It would work though if you'd write:
EDIT
You could try it with
In this case your
Foo
object should be automatically casted to a string.如果这对您的
Foo
对象有意义,您可以重载__add__
方法,如下所示:示例输出:
If that makes sense for your
Foo
object, you can overload the__add__
method as follows:Example output: