python如何通过实例方法名字调用方法

作者:北门吹雪 时间:2021-04-24 09:00:31 

本文实例为大家分享了python通过实例方法名字调用方法的具体代码,供大家参考,具体内容如下

案例:

       某项目中,我们的代码使用的2个不同库中的图形类:

              Circle,Triangle

       这两个类中都有一个获取面积的方法接口,但是接口的名字不一样

       需求:

              统一这些接口,不关心具体的接口,只要我调用统一的接口,对应的面积就会计算出来

如何解决这个问题?

定义一个统一的接口函数,通过反射:getattr进行接口调用


#!/usr/bin/python3

from math import pi

class Circle(object):
def __init__(self, radius):
 self.radius = radius

def getArea(self):
 return round(pow(self.radius, 2) * pi, 2)

class Rectangle(object):
def __init__(self, width, height):
 self.width = width
 self.height = height

def get_area(self):
 return self.width * self.height

# 定义统一接口
def func_area(obj):
# 获取接口的字符串
for get_func in ['get_area', 'getArea']:
 # 通过反射进行取方法
 func = getattr(obj, get_func, None)
 if func:
  return func()

if __name__ == '__main__':
c1 = Circle(5.0)
r1 = Rectangle(4.0, 5.0)

# 通过map高阶函数,返回一个可迭代对象
erea = map(func_area, [c1, r1])
print(list(erea))

通过标准库operator中methodcaller方法进行调用


#!/usr/bin/python3

from math import pi
from operator import methodcaller

class Circle(object):
def __init__(self, radius):
 self.radius = radius

def getArea(self):
 return round(pow(self.radius, 2) * pi, 2)

class Rectangle(object):
def __init__(self, width, height):
 self.width = width
 self.height = height

def get_area(self):
 return self.width * self.height

if __name__ == '__main__':
c1 = Circle(5.0)
r1 = Rectangle(4.0, 5.0)

# 第一个参数是函数字符串名字,后面是函数要求传入的参数,执行括号中传入对象
erea_c1 = methodcaller('getArea')(c1)
erea_r1 = methodcaller('get_area')(r1)
print(erea_c1, erea_r1)

来源:http://www.cnblogs.com/2bjiujiu/p/7289961.html

标签:python,实例,调用
0
投稿

猜你喜欢

  • Python中设置变量访问权限的方法

    2023-09-13 15:42:15
  • 利用ASP在线维护数据库

    2007-10-12 13:53:00
  • 一道python走迷宫算法题

    2022-08-11 19:14:25
  • asp中判断服务器是否安装了某种组件的函数

    2011-02-16 10:53:00
  • Python tkinter库绘制春联和福字的示例详解

    2022-03-05 06:29:04
  • 关于“简单,可依赖”

    2008-10-22 13:33:00
  • Python全栈之学习HTML

    2023-12-05 14:56:55
  • python selenium自动上传有赞单号的操作方法

    2023-05-21 13:24:43
  • MYSQL在一个字段值前面加字符串

    2010-10-14 14:28:00
  • php实现pdo数据库操作类过程详解

    2023-05-25 11:15:05
  • django实现前后台交互实例

    2022-04-12 20:53:33
  • 浅析MySQL并行复制

    2024-01-13 02:54:10
  • Python 中制作偶数列表的方法

    2022-08-20 20:15:56
  • Python机器学习实战之k-近邻算法的实现

    2022-02-06 03:02:09
  • Mysql连接本地报错:1130-host ... is not allowed to connect to this MySQL server解决

    2024-01-28 04:52:50
  • MySQL数据库磁盘优化

    2008-11-24 17:29:00
  • python多线程使用方法实例详解

    2023-08-18 17:34:00
  • php获取给定日期相差天数的方法分析

    2024-05-02 17:34:20
  • PHP中过滤常用标签的正则表达式

    2024-05-03 15:35:43
  • CentOS 7中升级MySQL 5.7.23的坑与解决方法

    2024-01-16 21:54:53
  • asp之家 网络编程 m.aspxhome.com