如何将`Object`与字符串连接?

20 投票
3 回答
19001 浏览
提问于 2025-04-17 13:08

如何将一个Object对象和一个字符串(基本类型)连接在一起,而不使用重载和显式类型转换(比如str())?

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'

是不是必须重载+这个操作符?还有其他方法吗(只是想问问)?

附注:我知道关于重载操作符和类型转换的事情(比如str(Foo('text'))

3 个回答

1

如果这样做对你的 Foo 对象有意义,你可以像下面这样重写 __add__ 方法:

class Foo:
    def __init__(self, text):
        self.text = text

    def __str__(self):
        return self.text

    def __add__(self, other):
        return str(self) + other

_string = Foo('text') + 'string'
print _string

示例输出:

textstring
7
_string = Foo('text') + 'string'

这行代码的问题在于,Python认为你想把一个字符串加到一个Foo类型的对象上,而不是反过来。

不过,如果你这样写的话,就可以正常工作:

_string = "%s%s" % (Foo('text'), 'string')

编辑

你可以试试这个:

_string = 'string' + Foo('text')

在这种情况下,你的Foo对象应该会自动转换成一个字符串。

26

只需要定义 __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)

这两个方法会根据你写的代码来决定哪个被调用。如果你写的是 Foo("b") + "a",那么就会调用 __add__();而如果你写的是 "a" + Foo("b"),那么就会调用 __radd__()

撰写回答