我必须使用重载运算符添加将两个名称添加到一起。我的输出应该是两个名字加在一起,例如:“john”+“frank”='JohnFrank'
class Person():
def __init__(self, name):
self.aname = name
def __add__(self,other):
x = self.person1
y = self.person2
print(x + y)
return(Couple(x,y))
class Couple(Person):
def __init__(self,person1,person2):
self.person1 = person1
self.person2 = person2
我做错了什么?
我得到的错误:
Traceback (most recent call last):
File "<pyshell#81>", line 1, in <module>
acouple = p1 + p2
File "/Users/Desktop/NameP.py", line 7, in __add__
x = self.person1
AttributeError: 'Person' object has no attribute 'person1'
答案 0 :(得分:1)
Person
对象只有aname
,因此您应该传递当前对象self
和添加的对象:
def __add__(self, other):
return Couple(self, other)
答案 1 :(得分:0)
# This is what worked for me
class Person():
def __init__(self, name):
self.aname = name
def __add__(self,other):
x = self.aname
y = self.aname
print(self.aname + " " + other.aname)
return(Couple(x,y))
class Couple(Person):
def __init__(self,person1,person2):
self.person1 = person1
self.person2 = person2
enter code here