美文网首页
python 通过字符串方式调用方法operator.metho

python 通过字符串方式调用方法operator.metho

作者: SkTj | 来源:发表于2019-12-04 11:06 被阅读0次

    最简单的情况,可以使用 getattr() :

    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) # Calls p.distance(0, 0)
    另外一种方法是使用 operator.methodcaller() ,例如:

    import operator
    operator.methodcaller('distance', 0, 0)(p)
    当你需要通过相同的参数多次调用某个方法时,使用 operator.methodcaller 就很方便了。 比如你需要排序一系列的点,就可以这样做:

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

    相关文章

      网友评论

          本文标题:python 通过字符串方式调用方法operator.metho

          本文链接:https://www.haomeiwen.com/subject/tjvcpctx.html