37. 通过实例方法名字的字符串调用方法

某项目中,代码使用了三个不同库中的图形类:CircleTriangleRectangle,它们都有一个获取图形面积的接口(方法),但方法名字不同。

要求:实现一个统一的获取面积的函数,使用各种方法名进行尝试,调用相应类的接口。

解决方案:

  1. 使用内置函数getattr(),通过名字获取方法对象,然后调用。

  2. 使用标准库operator下的methodcaller()函数调用。


  • 对于内置函数getattr()
getattr(object, name[, default])

返回对象命名属性的值。name必须是字符串。如果该字符串是对象的属性之一,则返回该属性的值。例如getattr(x, 'foobar') 等同于x.foobar。如果指定的属性不存在,且提供了default值,则返回它,否则触发AttributeError。

>>> s = 'abc123'

>>> s.find('123')
3

>>> getattr(s, 'find', None)('123')             #等同于s.find('123')
3
  • 对于methodcaller()函数:
operator.methodcaller(name[, args...])

methodcaller()函数会返回一个可调用对象,该对象在其操作数上调用方法名。如果提供了额外的参数或关键字参数,它们也将被提供给方法。

>>> from operator import methodcaller

>>> s = 'abc123abc456'

>>> s.find('abc', 3)
6

>>> methodcaller('find', 'abc', 3)(s)               #等价于s.find('abc', 3)
6

lib1.py

class Triangle:
    def __init__(self, a, b, c):
        self.a, self.b, self.c = a,b,c
    
    def get_area(self):
        a,b,c = self.a, self.b, self.c
        p = (a+b+c) / 2
        return (p * (p-a) * (p-b) * (p-c)) ** 0.5

lib2.py

class Rectangle:
    def __init__(self, a, b):
        self.a, self.b = a,b

    def getarea(self):
        return self.a * self.b

lib3.py

import math

class Circle:
    def __init__(self, r):
        self.r = r

    def area(self):
        return round(self.r ** 2 * math.pi, 1)
  • 方案1示例:
from lib1 import Triangle
from lib2 import Rectangle
from lib3 import Circle

def get_area(shape, method_name = ['get_area', 'getarea', 'area']):
    for name in method_name:
        f = getattr(shape, name, None)
        if f: return f()

shape1 = Triangle(3, 4, 5)
shape2 = Rectangle(4, 6)
shape3 = Circle(2)

shape_list = [shape1, shape2, shape3]
area_list = list(map(get_area, shape_list))
print(area_list)

[6.0, 24, 12.6]             #结果
  • 方案2示例:
from lib1 import Triangle
from lib2 import Rectangle
from lib3 import Circle
from operator import methodcaller

def get_area(shape, method_name = ['get_area', 'getarea', 'area']):
    for name in method_name:
        if hasattr(shape, name):
            return methodcaller(name)(shape)

shape1 = Triangle(3, 4, 5)
shape2 = Rectangle(4, 6)
shape3 = Circle(2)

shape_list = [shape1, shape2, shape3]
area_list = list(map(get_area, shape_list))
print(area_list)

[6.0, 24, 12.6]             #结果

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值