python 7-8 如何通过实例方法名字的字符串调用方法/使用getattr/标库operator下的methodcaller函数

python 7-8 如何通过实例方法名字的字符串调用方法/使用内置函数getattr/标库operator下的methodcaller函数

方法1.使用内置函数getattr,通过名字在实例上获取方法对象,然后调用

def getArea(shape):
for name in (‘area’,’getArea’,’get_area’):
f = getattr(shape,name,None)
if f:
return f()

方法2.使用标注库operator下的methodcaller函数调用

from operator import methodcaller
s=”abc123abc”
s.find(‘abc’,4)
6

methodcaller(‘find’,’abc’,4)(s)
6

for name in ('area','getArea','get_area'):
    f = getattr(shape,name, None)
    if f:
        return methodcaller(name)(shape)
from math import pi
from operator import methodcaller
class Circle(object):
    def __init__(self,r):
        self.r = r
    def area(self):
        return self.r **2 * pi

class Triangle(object):
    def __init__(self,a,b,c):
        self.a = a
        self.b = b
        self.c = c

    def getArea(self):
        a,b,c=self.a,self.b,self.c
        p=(a + b + c) / 2
        area = (p * (p - a) * (p -b ) * (p - c)) ** 0.5
        return area

class Rectangle(object):
    def __init__(self,w,h):
        self.w = w
        self.h = h

    def get_area(self):
        return self.w * self.h

def getArea(shape):
    for name in ('area','getArea','get_area'):
        f = getattr(shape,name,None)
        if f:
            return f()


def getArea2(shape):
    for name in ('area','getArea','get_area'):
        f = getattr(shape,name, None)
        if f:
            return methodcaller(name)(shape)

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

shapes=[shape1,shape2,shape3]


print map(getArea,shapes)
print map(getArea2,shapes)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值