the 'in' operator and class instances
Michele Simionato
mis6 at pitt.edu
Sun Jun 8 08:56:35 EDT 2003
"Vinoo vasudevan" <ee01b092 at ee.iitm.ernet.in> wrote in message news:<mailman.1055063152.22684.python-list at python.org>...
> Hi,
> I'm an newbie and have been getting to know Python over the past two weeks.
> One of the things I really liked was the 'in' operator. Statements like "key
> in dict" or "line in file" are really cool. But this doesn't seem to work for
> classes. i.e.
>
> >>> class a:
> def f(self):
> pass
>
> >>> 'f' in a
> <Traceback>
>
> Could somebody tell me why class instances don't use in to check for
> memebership i.e. something like hasattr(..). I read up on "__contains__" in
> the Language Reference. Couldn't python just define a default version of this
> for all classes/instances to check for membership. Any class that attaches a
> special meaning to membership can of course define its own "__contains__". In
> c++ terminology (my __previous__ language :-) ) : can't "object" define a
> virtual function "__contains__"? Just a suggestion. Plz let me know if I don't
> have a clue of I'm talking about. :-)
>
Why would your force __contains__ meaning always "hasattr" ?
Often it is not what you want. Look for instance at this example:
class GeometricFigure(object):
"""This class allows to define geometric figures according to their
equation in the cartesian plane. Moreover addition and subtraction
of geometric figures are defined as union and subtraction of sets,
and the syntax (x,y) in <figure> is recognized."""
def __init__(self,equation,**parameters):
"Initialize "
self.eq=equation
self.par=parameters
for (k,v) in self.par.items(): #replaces the parameters
self.eq=self.eq.replace(k,str(v))
self.contains=eval('lambda x,y : '+self.eq)
def combine(self,fig,operator):
"""Combine self with the geometric figure fig, using the
operators "or" (addition) and "and not" (subtraction)"""
comboeq="("+self.eq+")"+operator+"("+fig.eq+")"
return GeometricFigure(comboeq)
def __add__(self,fig):
"Union of sets"
return self.combine(fig,' or ')
def __sub__(self,fig):
"Subtraction of sets"
return self.combine(fig,' and not')
def __contains__(self,point): #point is a tuple (x,y)
return self.contains(*point)
disk=GeometricFigure('(x-x0)**2+(y-y0)**2 <= r**2', x0=0,y0=0,r=5)
# creates a disk of radius 5 centered in the origin
print (1,2) in disk #asks if the point (1,2) is inside the disk (True)
print (4,4) in disk #asks if the point (4,4) is inside the disk (False)
More information about the Python-list
mailing list