getattr函数和map函数的使用
getattr()函数
描述
getattr() 函数用于返回一个对象属性值。
语法
getattr(object, name[, default])
参数
- object – 对象。
- name – 字符串,对象属性。
- default – 默认返回值,如果不提供该参数,在没有对应属性时,将触发 AttributeError。
使用
- 代码举例说明
class A(object): a = 2 def f(self): print("fff") a = A() # 实例化一个对象 print(getattr(a, 'a')) # 获取a的属性值2 # print(getattr(a, 'b')) # b不存在,触发异常AttributeError: 'A' object has no attribute 'b' print(getattr(a, 'b', None)) # 设置默认值,b不存在,返回None print(getattr(a, 'f', None)) # 如果f方法存在,则返回A.f b = getattr(a, 'f', None) # 返回后可以直接使用 b()
map()函数
map(func,iterable)
–> 将iterable中的元素一一映射到func函数中处理,并且返回新的map对象。
注意:Python 2.x map返回列表。Python 3.x map返回迭代器。
- 代码举例说明
def func(i): return i ** 2 x = [1, 2, 3, 4] y = map(func, x) # y接收一个迭代器 print(list(y)) # 以列表形式输出[1, 4, 9, 16]
getattr()和map()联合使用
- 代码举例说明
class Circle(object): def __init__(self, r): self.radius = r def get_square(self): s = 3.14159 * self.radius ** 2 return s class Triangle(object): def __init__(self, a, b, c): self.a, self.b, self.c = a, b, c def get_square(self): p = (self.a + self.b + self.c) / 2 s = (p * (p - self.a) * (p - self.b) * (p - self.c)) ** 0.5 return s class Rectangle(object): def __init__(self, a, b): self.a, self.b = a, b def get_square(self): s = self.a * self.b return s def square(shape): """定义一个函数,判断是否有get_square方法""" func = getattr(shape, 'get_square', None) if func: # 如果存在get_square方法,那么直接使用 return func() circle = Circle(5) # 实例化圆对象 triangle = Triangle(3, 4, 5) # 实例化三角形对象 rectangle = Rectangle(5, 6) # 实例化矩形对象 shape = [circle, triangle, rectangle] # 定义一个列表存储三个实例化对象 s = list(map(square, shape)) # 使用map函数,将shape中的元素一一映射到square函数中处理 print(s) # 输出结果[78.53975, 6.0, 30]
最后,有喜欢博主写的内容的伙伴可以收藏加关注哦!