python面试题——Python中怎么通过反射来调用对象的函数?

在人生的道路上,不管是潇洒走一回,或者是千山独行,皆须是自己想走的路,虽然,有的人并不是很快就能找到自己的方向和道路,不过,只要坚持到底,我相信,就一定可以找到自己的路,只要找到路,就不必怕路途遥远了。

导读:本篇文章讲解 python面试题——Python中怎么通过反射来调用对象的函数?,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

在这里插入图片描述

先做一个案例:不利用反射,计算2个点之间的距离

import math

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

    # 计算两点之间的直线距离
    def distance(self, other):
        return math.hypot(self.x - other.x, self.y - other.y)


if __name__ == '__main__':
    p1 = Point(2, 3)
    p2 = Point(0, 0)
    print(p1.distance(p2))

执行结果:3.6055512754639896

方法一: 利用反射,最简单的情况,可以使用 getattr()

动态编程才会用到反射

场景:假如原始的一个Point类中定义了distance方法,之后由于业务需求我又在类中又偷偷的定义了distance2方法,但是其他程序员不知道我做了什么改动,我直接告诉他函数名和函数实现的方法就可以了,当他调用类中的distance2方法时就不需要看代码逻辑了。

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

    # 计算两点之间的直线距离
    def distance(self, other):
        return math.hypot(self.x - other.x, self.y - other.y)

    # 计算两点之间的直线距离
    def distance2(self, other):      新加的方法
        return math.hypot(self.x - other.x, self.y - other.y)


调用任意对象中的任意函数
def method_call(o,method_name,args):
    return getattr(o,method_name)(args)


# todo 下面的代码早就写好了
if __name__ == '__main__':
    p1 = Point(2, 3)
    p2 = Point(0, 0)            #原点

    #动态编程才会用到反射
    print(method_call(p1,'distance2',p2))

方法二:利用反射,operator.methodcaller

methodcaller:返回一个在操作数上调用 name 方法的可调用对象。 如果给出额外的参数和/或关键字参数,它们也将被传给该方法。

import  math
import operator
class Point():

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

    # 计算两点之间的直线距离
    def distance(self, other):
        return math.hypot(self.x - other.x, self.y - other.y)

    # 计算两点之间的直线距离
    def distance2(self, other):  # todo 新加的方法
        return math.hypot(self.x - other.x, self.y - other.y)

# todo 下面的代码早就写好了
if __name__ == '__main__':
    p1 = Point(2, 3)
    p2 = Point(0, 0)            #原点

    import operator
    print(operator.methodcaller('distance2',p2)(p1))

在这里插入图片描述

在这里插入图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/123218.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!