getattr:判断类、对象或者模块中是否有相应的属性或方法
用法
getattr(obj, str, default=None)
- 判断obj中是否有str属性,有就返回,没有时如果有传入第三参数就返回第三参数,没有就报错
例子1:下面两个函数等价
>>> print(p.__dict__)
{'x': 4, 'y': 16}
>>> print(getattr(p, '__dict__'))
{'x': 4, 'y': 16}
getattr()使用方法
>>> p = Point(4, 5)
>>> getattr(p, "x")
4
>>> getattr(p, "y")
16
>>> print(getattr(p, '__dict__'))
{'x': 4, 'y': 5}
>>> getattr(p, "z", "NotFound")
'NotFound'
>>> getattr(p, "z")
Traceback (most recent call last):
File "D:\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3331, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-15-83b506d04926>", line 1, in <module>
getattr(p, "z")
AttributeError: 'Point' object has no attribute 'z'
settattr
- 设置属性object的属性,存在则覆盖,不存在则新增。第三参数为新的属性值。
setattr(object, name, value)
1.例子:settattr()使用方法
>>> p1 = Point(4, 5)
>>> p2 = Point(10, 10)
>>> print(p1.__dict__)
{'x': 4, 'y': 5}
>>> print(p2.__dict__)
{'x': 10, 'y': 10}
>>> setattr(p1, 'y', 16)
>>> setattr(p1, 'z', 10)
>>> print(p1.__dict__)
{'x': 4, 'y': 16, 'z': 10}