python - 相等运算符覆盖问题

标签 python

我是 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/

相关文章:

python - GitPython 并向 Git 对象发送命令

python - 为什么扩展模板时我的表单不起作用

python:两种方式的部分信用卡存储加密

python - 我想创建一个可以在 python 中分析下载的文本文件的程序

Python 根本无法工作

python - 哪个占用更少的内存,卡住集或元组?

python - 我如何正确地转义这些引号?

python - Django - 如何在应用程序中共享配置常量?

python - 在 python 中,使用一个图像的 RGB 值在另一个图像中创建感兴趣区域

python - 为什么后来声明的小部件首先出现?