反射
反射
反射指的是通过 ”字符串“ 对对象的属性或方法进行操作。
反射的方法有:
hasattr:通过 ”字符串“ 判断对象的属性或方法是否存在
getattr:通过 ”字符串“ 获取对象的属性值或方法
setattr:通过 ”字符串“ 设置对象的属性值
delattr:通过 ”字符串“ 删除对象的属性或方法
注意:反射的四个方法都是python内置
1、hasattr
通过 ”字符串“ 判断对象的属性或方法是否存在
class Foo:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def func(self):
pass
foo_obj = Foo(10, 20, 30)
# hasattr:通过字符串 "x"、"y"、"z" 判断对象中是否存在属性
print(hasattr(foo_obj, "x"))
print(hasattr(foo_obj, "y"))
print(hasattr(foo_obj, "z"))
# hasattr:通过字符串 "func" 判断对象中是否存在该方法
print(hasattr(foo_obj, "func"))

![反射[Python常见问题]](https://www.zixueka.com/wp-content/uploads/2023/10/1696830882-53c351f7ca61ae3.jpg)
