有没有办法在本地覆盖 __eq__ 函数/运算符并在之后恢复旧的? [英] Is there any way to override locally the __eq__ function/operator and restore the old one after?

查看:42
本文介绍了有没有办法在本地覆盖 __eq__ 函数/运算符并在之后恢复旧的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在受限范围内进行对象之间的自定义比较,有没有办法做到这一点并且不污染运算符,例如之后恢复之前的eq?

I need to make a custom comparison between objects during a restricted scope, is there any way to do that and without polluting the operator, eg restore the previous eq afterwards ?

class Test():
    def __eq__(self, i):
        print "eq lvl 1"

def test(a , b):
    def _itest(i):
        print "eq lvl 2"

>>> a = Test()
>>> b = Test()
>>> a == b
eq lvl 1
>>> test(a, b)
>>> a == b
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: _itest() takes exactly 1 argument (2 given)

我这样做是因为在特定条件下我需要降低 eq 运算符的性能.

I'm doing so because given certain condition I need to degrade the eq operator.

注意:我想覆盖 __eq__ 以使用 in 语句.

Note: I want to override __eq__ in order to use the in statement.

推荐答案

您的样本太小,所以我会尝试推断...

Your sample is too small so I'll try to extrapolate...

def somewhere():
  old_eq = obj.__eq__
  def new_eq(a, b):
    return False
  obj.__eq__ = new_eq
  # ^^^ Will fail here because you can't assign new __eq__ to the object
  if not obj == obj:
    print('Well, ok...')
  obj.__eq__ = old_eq

您仍然可以尝试使用可配置的(通过钩子)__eq__ 方法制作您自己的对象,并用这个方法替换您的对象,例如:

You still can try making you own object with configurable (via hooks) __eq__ method and substitute your object with this one, like:

class Patched(YourClass):
  def __eq__(self, i):
    if self.original__eq:
      return YourClass.__eq__(self, i):
    else:
      pass # your code here

这篇关于有没有办法在本地覆盖 __eq__ 函数/运算符并在之后恢复旧的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆