getattr:判断类、对象或者模块中是否有相应的属性或方法

用法

  1. getattr(obj, str, default=None)
  • 判断obj中是否有str属性,有就返回,没有时如果有传入第三参数就返回第三参数,没有就报错

例子1:下面两个函数等价

  1. >>> print(p.__dict__)
  2. {'x': 4, 'y': 16}
  3. >>> print(getattr(p, '__dict__'))
  4. {'x': 4, 'y': 16}

getattr()使用方法

  1. >>> p = Point(4, 5)
  2. >>> getattr(p, "x")
  3. 4
  4. >>> getattr(p, "y")
  5. 16
  6. >>> print(getattr(p, '__dict__'))
  7. {'x': 4, 'y': 5}
  8. >>> getattr(p, "z", "NotFound")
  9. 'NotFound'
  10. >>> getattr(p, "z")
  11. Traceback (most recent call last):
  12. File "D:\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3331, in run_code
  13. exec(code_obj, self.user_global_ns, self.user_ns)
  14. File "<ipython-input-15-83b506d04926>", line 1, in <module>
  15. getattr(p, "z")
  16. AttributeError: 'Point' object has no attribute 'z'

settattr

  • 设置属性object的属性,存在则覆盖,不存在则新增。第三参数为新的属性值。
  1. setattr(object, name, value)

1.例子:settattr()使用方法

  1. >>> p1 = Point(4, 5)
  2. >>> p2 = Point(10, 10)
  3. >>> print(p1.__dict__)
  4. {'x': 4, 'y': 5}
  5. >>> print(p2.__dict__)
  6. {'x': 10, 'y': 10}
  7. >>> setattr(p1, 'y', 16)
  8. >>> setattr(p1, 'z', 10)
  9. >>> print(p1.__dict__)
  10. {'x': 4, 'y': 16, 'z': 10}