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

yipeiwu_com7年前Python基础

本文实例为大家分享了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)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

网站渗透常用Python小脚本查询同ip网站

网站渗透常用Python小脚本查询同ip网站

旁站查询来源: http://dns.aizhan.com http://s.tool.chinaz.com/same http://i.links.cn/sameip/ http://...

Python语言生成水仙花数代码示例

Python语言生成水仙花数代码示例

水仙花数是指一个 n 位数 ( n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身。 本文将通过Python代码实现打印水仙花数,具体如下: #水仙花数 #narcissist...

python selenium执行所有测试用例并生成报告的方法

直接上代码。 # -*- coding: utf-8 -*- import time import os import os.path import re import unitte...

浅谈Python 递归算法指归

浅谈Python 递归算法指归

1. 递归概述 递归( recursion)是一种编程技巧,某些情况下,甚至是无可替代的技巧。递归可以大幅简化代码,看起来非常简洁,但递归设计却非常抽象,不容易掌握。通常,我们都是自上...

详解python中递归函数

函数执行流程 def foo1(b,b1=3): print("foo1 called",b,b1) def foo2(c): foo3(c) print...