我是 python 的新手,这是我的类(class)
class Goal:
def __init__(self, name, value):
self.name = name
self.value = value
def is_fulfilled(self):
return self.value == 0
def fulfill(self, value):
if(self.value < value):
value = self.value
self.value -= value
def debug(self):
print "-----"
print "#DEBUG# Goal Name: {0}".format(self.name)
print "#DEBUG# Goal Value: {0}".format(self.value)
print "-----"
def __eq__(self, other):
return self.name == other.name
当我这样做
if(goal1 == goal2):
print "match"
它引发了这个错误
File "/home/dave/Desktop/goal.py", line 24, in __eq__
return self.name == other.name
AttributeError: 'str' object has no attribute 'name'
我在这里做错了什么?
最佳答案
回溯似乎表明您的 goal2 是一个字符串对象,而不是一个 Goal 对象 但您可以这样做来保护自己:
def __eq__(self, other):
try:
return self.name == other.name
except AttributeError:
return False
关于python - 相等运算符覆盖问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5840746/