<!-- language: lang-py -->
class File:
### Сlass initialization
def __init__(self, path, name, size, date):
self.path = path
self.name = name
self.size = size
self.date = date
def __eq__(self, other):
# if self.name == other.name and self.size == other.size and self.date == other.date:
if self.name == other.name and self.size == other.size:
# if self.size == other.size and self.date == other.date:
return True**
def __eq__(self, other):
# if self.name == other.name and self.size == other.size and self.date == other.date:
if self.name == other.name and self.size == other.size:
# if self.size == other.size and self.date == other.date:
return True
发生特定情况时必须触发不同的变种
答案 0 :(得分:1)
嗯,这当然是可能的:
class Foo(object):
def __init__(self, x):
self.x = x
def __eq__(self, other):
return other.x == self.x
foo1 = Foo(1)
foo2 = Foo(2)
print (foo1 == foo2)
def new_eq(self, other):
return other.x - 1 == self.x
Foo.__eq__ = new_eq
print (foo1 == foo2)
说明:
__eq__
是类Foo
的属性,它是绑定到类的函数(类方法)。您可以将__eq__
属性设置为新函数以替换它。请注意,因为这是修改类,所有实例都会看到一个更改,包括已经实例化的foo1
和foo2
。
所有这一切,这是一个非常粗略的做法,特别是像__eq__
之类的东西,所以我想说这可能不是你的问题的一个很好的解决方案,但不知道那个问题是什么,我我只想说如果我在代码中看到这种东西,那会让我很紧张。
答案 1 :(得分:0)
不是动态地交换__eq__
,为什么不在调用__eq__
时使用条件来确定使用哪种情况?
class Foo:
def __eq__(self, other):
if (self._condition_1):
return self._eq_condition_1(other)
elif (self._condition_2):
return self._eq_condition_2(other)
else:
return self._eq_condition_default(other)
def _eq_condition_1(self, other):
return True
def _eq_condition_2(self, other):
return False
def _eq_condition_default(self, other):
return True