list, object and matching...
Alex Martelli
aleax at aleax.it
Fri May 10 04:18:36 EDT 2002
Shagshag wrote:
> Having a class with, for example, 3 private attributes a, b, c.
> Having a python list (or maybe something which inherits from it) which
> contains objects from this class.
>
> How can i do to have :
>
> - objecti == objectj only if attribute a and b are equal (c doesn't
> need to be checked)
>
> - list.index(objectk) => searching for an object contained in list but
> which match only attribute a and b
Python 2.2.1 (#1, Apr 15 2002, 17:55:14)
[GCC 2.96 20000731 (Mandrake Linux 8.1 2.96-0.62mdk)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class shag:
... def __init__(self, a, b, c):
... self.a=a
... self.b=b
... self.c=c
... def __eq__(self, other):
... try: return self.a==other.a and self.b==other.b
... except AttributeError: return False
...
>>> s1 = shag(1,2,3)
>>> s2 = shag(1,2,4)
>>> s1==s2
1
>>> s1==23
0
>>> alist = [1, 2, s1, 3, 4, s2, 5, 6]
>>> alist.index(s2)
2
>>>
Alex
More information about the Python-list
mailing list