python学习笔记__反射
反射 # 通过字符串的形式对对象中的成员进行操作(获取/查找/添加/删除)。
操作的内置函数:
1.获取 getattr(object, name)
# 去对象object中获取name的内容
class Foo: def __init__(self, name, age): self.name = name self.age = age obj = Foo('Lemon147', 18) v = getattr(obj, 'name') print(v) >>> Lemon147 add = getattr(obj, 'add', 'not find!') #如果对象obj中有属性add则返回self.add的值,否则返回'not find'! print(add) >>> not find!
2.查找 hasattr(object, name)
# 检查对象object中是否有name
class Foo: def __init__(self, name, age): self.name = name self.age = age obj = Foo('Lemon147', 18) setattr(obj, 'add', '123') print(getattr(obj, 'add')) delattr(obj, 'add') add = hasattr(obj, 'add') print(add) >>>False
3.添加 setattr(object, name,value)
# 在对象object中设置name的值为value
class Foo: def __init__(self, name, age): self.name = name self.age = age obj = Foo('Lemon147', 18) setattr(obj, 'add', '123') add = hasattr(obj, 'add') print(add) >>> True print(getattr(obj, 'add')) >>>123
4.删除 delattr(object, name)
# 删除对象object中的成员name
class Foo: def __init__(self, name, age): self.name = name self.age = age obj = Foo('Lemon147', 18) setattr(obj, 'add', '123') print(getattr(obj, 'add')) delattr(obj, 'add') add = hasattr(obj, 'add') print(add)
注:getattr,hasattr,setattr,delattr对模块的修改都在内存中进行,并不会影响文件中真实内容。
应用场景
根据输入或选择,动态的调用不同的模块或功能。(同字典-dictionary 通过key,查询对应的value类似。)
def s1(): return '首页' def s2(): return '新闻' def s3(): return '精华'
import test002 foo = True while foo: inp = input('请输入您要查询的内容,输入‘Q’退出:') #输入‘s1’执行‘首页’ if hasattr(test002, inp): v = getattr(test002, inp) print(v()) elif inp == 'Q': break else: print('输入有误')