In the method of the object as a string for the name of the regulated

Call the object's methods are generally divided into two steps, first looks for an object attribute contains the method name, and then call the function.
For simple cases, may be used getattr (), as follows:

import math

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __repr__(self):
        return 'Point({!r:},{!r:})'.format(self.x, self.y)

    def distance(self, x, y):
        return math.hypot(self.x - x, self.y - y)

p = Point(2, 3)
d = getattr(p, 'distance')(0, 0)

Another solution is to use the operator module methodcaller () function, as follows:

import operator
operator.methodcaller('distance', 0, 0)(p)

If you find a method by name and once again provide the same parameters, operator.methodcaller () may be useful. as follows:

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))

Call the method is actually two separate steps, involving property lookup and function calls. Therefore, to call a method, just use getattr () to find property, just as any other properties the same. To as a result of the method call, simply as a function of the search results.

Guess you like

Origin www.cnblogs.com/jeffrey-yang/p/12159050.html