class A:
def __init__(self, text):
self.text = text
def __repr__(self):
return self.text
def __str__(self):
return self.text
def __add__(self, other):
return str(self) + other
def __radd__(self, other):
return other + str(self)
我希望A对象列表与str.join()“可连接”.
我应该实现哪个special method来实现这个目标?
当然,我可以首先提取一个文本列表然后加入它,但这不是我想要的.
b = A('Hello')
c = A('World')
l = [b, c]
print b, c
print l
print b + ' ' + c
print ' '.join(l) #
Hello World
[Hello, World]
Hello World
Traceback (most recent call last):
File "sandbox.py", line 24, in
print ' '.join(l)
TypeError: sequence item 0: expected string, instance found