如何用字符串连接`Object`?

tom*_*mas 11 python casting

如何连接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__())来呼叫.

  • IMO 这不是一个好的做法。显式调用“str”是正确的模式。不管怎样,你仍然在这里调用“str”,你只是隐藏了它。 (2认同)

Con*_*ius 5

_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对象应该自动转换为字符串。

  • Python 不存在将对象转换为字符串这样的事情。要么“__add__”方法会显式地执行此操作,要么没有人会执行此操作。 (2认同)