October 2024
Beginner
5 pages
2m
English
You have the name of a method that you want to call on an object stored in a string, and you want to execute the method.
For simple cases, you might use getattr(), like this:
importmathclassPoint(object):def__init__(self,x,y):self.x=xself.y=ydef__repr__(self):return'Point({!r:},{!r:})'.format(self.x,self.y)defdistance(self,x,y):returnmath.hypot(self.x-x,self.y-y)p=Point(2,3)d=getattr(p,'distance')(0,0)# Calls p.distance(0, 0)
An alternative approach is to use operator.methodcaller(). For example:
importoperatoroperator.methodcaller('distance',0,0)(p)
operator.methodcaller() may be useful if you want to look up a
method by name and supply the same arguments over and over again. For
instance, if you need to sort an entire list of points:
points=[Point(1,2),Point(3,0),Point(10,-3),Point(-5,-7),Point(-1,8),Point(3,2)]# Sort by distance from origin (0, 0)points.sort(key=operator.methodcaller('distance',0,0))
Calling a method is actually two separate steps involving an attribute
lookup and a function call. Therefore, to call a method, you simply look
up the attribute using getattr(), as for any other attribute. To invoke the result as a method, simply treat ...
Read now
Unlock full access