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

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

# 我们有三个图形类
# Circle,Triangle,Rectangle
# 他们都有一个获取图形面积的方法,但是方法名字不同,我们可以实现一个统一
# 的获取面积的函数,使用每种方法名进行尝试,调用相应类的接口

# import math

# 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
#
#
# class Rectangle:
#     def __init__(self,a,b):
#         self.a,self.b = a,b
#
#     def getArea(self):
#         return self.a * self.b
#
# class Circle:
#     def __init__(self,r):
#         self.r = r
#
#     def area(self):
#         # return self.r ** 2 * math.pi
#         return self.r ** 2 * 3.14159


# from lib1 import Triangle
# from lib2 import Rectangle
# from lib3 import Circle

shape1 = Triangle(3, 4, 5)    # 三角形   实例化
shape2 = Rectangle(4, 6)      # 矩形
shape3 = Circle(1)            # 圆

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


# print(get_area(shape2))  # 24
# print(get_area(shape1))   # 6.0
# print(get_area(shape3))     # 3.14159

# 用map函数调用(map会对提供的函数对指定序列作映射)
shape_list = [shape1,shape2,shape3]
arcs_list = list(map(get_area,shape_list))
print(arcs_list)
print(list(map(get_area,shape_list)))


# def demo(x):
#     return x ** 2
# demo(2)    # --> 4
# map(demo,[1,2,3])   # --> <map at 0x1b1cdc1ea58>
# list(map(demo,[1,2,3]))  # -->[1,4,9]

发布了106 篇原创文章 · 获赞 0 · 访问量 2391

猜你喜欢

转载自blog.csdn.net/weixin_45905671/article/details/105260433