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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013679490/article/details/54767170

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)

博主设置当前文章不允许评论。

没有更多推荐了,返回首页