美文网首页
python(Class8)

python(Class8)

作者: OldSix1987 | 来源:发表于2016-09-11 10:52 被阅读14次

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


    内置函数getattr
    标准库operator下的methodcaller函数

    
    
    
    class Circle(object):
        def __init__(self, r):
            self._r = r
    
        def area(self):
            return self._r ** 2 * 3.14
    
    
    class Rectangle(object):
        def __init__(self, w, h):
            self._w = w
            self._h = h
    
        def get_area(self):
            return self._w * self._h
    
    
    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
            return (p*(p-a)*(p-b)*(p-c)) ** 0.5
    
    
    def getarea(shape):
        for name in ('area', 'get_area', 'getArea'):
            f = getattr(shape, name, None)
            if f:
                return f()
    
    shape1 = Circle(2)
    shape2 = Rectangle(6, 4)
    shape3 = Triangle(3, 4, 5)
    
    shapes = [shape1, shape2, shape3]
    
    print(list(map(getarea, shapes)))
    
    

    相关文章

      网友评论

          本文标题:python(Class8)

          本文链接:https://www.haomeiwen.com/subject/rpjuettx.html