考虑一个类,它支持对字符串的强制转换,并在第二个操作数为字符串时支持连接(Python ):
$ cat dunder.py
class Foo:
def __str__(self):
return "foo"
def __add__(self, second):
return str(self) + str(second)
f = Foo()
print(f)
print(f + "bar")
print("bar" + f)print(f)和print(f + "bar")方法按预期的方式输出到屏幕。但是,print("bar" + f)方法如预期一样抛出一个异常:
$ python3 dunder.py
foo
foobar
Traceback (most recent call last):
File "dunder.py", line 12, in <module>
print("bar" + f)
TypeError: can only concatenate str (not "Foo") to str当类是执行连接的str 类的dunder方法时,如何修改类以支持字符串连接?
注意,我不想扩展str类,我对一般情况感兴趣。
发布于 2022-10-19 08:27:56
您需要实现__radd__方法,它是一个右侧添加,在标准__add__失败时用作回退。它在add操作中在右侧对象上被调用,左对象是它的其他参数,因此您需要以相反的顺序执行连接。
class Foo:
def __str__(self):
return "foo"
def __add__(self, second):
return str(self) + str(second)
def __radd__(self, second):
return str(second) + str(self)
f = Foo()
print(f)
print(f + "bar")
print("bar" + f)https://stackoverflow.com/questions/74122119
复制相似问题