类型错误: + 不支持的操作数类型:"行"和"行"



这里是代码:

class line:
def __init__(self, name):
self.name = name
def __str__(self):
return f"< {self.name} >"
print(line('te') + line('st'))

这就是我得到的错误:

Traceback (most recent call last):
File "C:UsersronilDocumentsCalculatormain.py", line 9, in <module>
print(line('roni') + line('levin'))
TypeError: unsupported operand type(s) for +: 'line' and 'line'

代码输出必须是"0"<te st>quot;类行给出了新的变量类型;print(line('te'(+line('st'(("需要加入";te";以及";st";有新型

您定义了对象的字符串表示,但您只是添加了对象,而不是它们的字符串表示。正如@MisterMiyagi所说,您会收到一条错误消息,因为Python正在对象中搜索__add__()方法,但没有找到。由于我不认为添加实际对象是您的目标,所以只需使用str()来获得字符串,然后可以将其连接:

print(str(line('te')) + str(line('st')))
# < te >< st >

或者使用f-string表示法,它会自动调用对象上的字符串方法:

print(f"{line('te')}{line('st')}")
# < te >< st >

如果你真的想添加对象,定义一个__add__()方法:

def __add__(self, other):
return line(self.name + other.name)
print(line('te') + line('st'))
# < test >

最新更新