【问题标题】:python custom class operator overloadingpython自定义类运算符重载
【发布时间】:2013-08-15 03:33:51
【问题描述】:

假设我有一堂课:

class Cat:
    def __init__(self, name = "default", age = 0):
        self.name = name
        self.age = age

我还有一份猫的清单:

l = [Cat('Joe')]

现在我无法调用以下内容:

if 'Joe' in l: # the right syntax would be if Cat('Joe') in list

我需要重载哪个运算符才能identify 类 Cat by 的成员变量 name 的对象?

【问题讨论】:

  • 我猜它是相等运算符,您可以在其中检查另一个对象是否属于同一实例,并且它的 name 属性与当前对象的名称匹配:__eq__(self, other): #todo check if other is ame type and if name matches self.name 定义相等运算符的行为,== .抱歉,我是 C# 人...

标签: python class oop operator-overloading


【解决方案1】:

你要定义__eq__方法,如下图:

class Cat:

    def __init__(self, name = "default", age = 0):
        self.name = name
        self.age = age

    def __eq__(self, other):
        if isinstance(other, str):
            return self.name == other
        elif isinstance(other, Cat):
            return self.name == other.name

这样当您运行检查时:

l = [Cat('Joe')]

'Joe' in l
#True

【讨论】:

  • OP 也应该定义 __hash__() 以便它与集合/字典一起使用。见the data model documentation
  • 对不起,isinstance 是什么?为什么你需要那个 if 语句?
  • @gen 在这种情况下isinstance 检查other 是否是一个字符串 (str) 或另一个Cat,告诉__eq__ 在每种情况下要做什么...
  • 我还有一个问题:如果我执行以下操作:for catname in l: print catname 它会打印 Cat 类的对象还是只打印对象的名称?
  • 打印可以将__str__()定义为explained here的对象
【解决方案2】:

list 对象上的__contains__ 是通过检查是否相等来实现的,因此覆盖__eq__

class Cat:
    def __init__(self, name = "default", age = 0):
        self.name = name
        self.age = age
    def __eq__(self, other):
        return self.name == other

这与排序无关,因为当左侧不支持该操作时,相等性检查会交换其参数。

如果您希望它与基于哈希的容器一起使用(例如 setdict),您还必须覆盖 __hash__

    def __hash__(self):
        return hash(self.name)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多