首页 > 代码库 > python反射及其attr系列案例

python反射及其attr系列案例

技术分享
 1 class People:
 2     """
 3  hasattr,setattr,getattr,delattr原理:所有的对象或者类如果有设定相应的key,value,那么在对应的__dict__
 4     这个返回值中都有key,value存在的,
 5 
 6     """
 7     def __init__(self,name):
 8         self.name = name
 9     def walk(self):
10         print(%s 瞧,\‘piter\‘ 正在奔跑% self.name)
11 P1 = People(lucy)
12 if hasattr(P1,name):  #判定如果调用对象P1有name属性,返回True,否则返回False
13     print(P1.__dict__[name]) #lucy
14 
15 if hasattr(P1,age):
16     print(P1.__dict__[age])
17 else:
18     setattr(P1,age,18)
19     print(P1.__dict__) #{‘age‘: 18, ‘name‘: ‘lucy‘}
20 if hasattr(P1,age):
21     delattr(P1,age)  #删除age属性
22 print(P1.__dict__) #{‘name‘: ‘lucy‘}
反射之四大内置函数

#下面是一个菜单的案例,类似反射(反射本质就是把字符串转成对象

技术分享
 1 def search():
 2     print(print search content)
 3 def add():
 4     print(add content)
 5 def delete():
 6     print(delete)
 7 def modify():
 8     print(modify)
 9 cmd_dict = {search:search,add:add,delete:delete,modify:modify}
10 while True:
11     count = 0
12     for i in cmd_dict.keys():
13         count += 1
14         print("%s\t%s"%(count,i))
15     opt = input("请输入选项>>> ")
16     if not opt:continue
17     if opt in cmd_dict:
18         func = cmd_dict.get(opt)
19         func()
菜单案例

内置attr:__getattr__,__setattr__,__delattr__

技术分享
 1 class Foo:
 2     def __init__(self,name):
 3         self.name = name
 4 
 5     def __getattr__(self, item):  #当属性不存在的情况下才会执行,否则不执行
 6         """如果被调用属性存在就不执行这里定义的代码块,否则的话,会执行这里的代码块"""
 7         print(get------%s%item,type(item))
 8 
 9     def __setattr__(self,key,value):
10         """设置值,实际上是往调用对象那个__dict__里设定key,并给相应的value"""
11         if not isinstance(value,str):raise  TypeError("must be str")
12         self.__dict__[key] = value
13         print(set ----Key:%s,value:%s%(key,value),type(key),type(value))
14     def __delattr__(self, item):
15         """删除属性,实际上是把调用对象的__dict__里删除指定的key"""
16         self.__dict__.pop(item)
17         print(delete item:%s%item,type(item))
18 
19 F = Foo(lucy)
20 print(F.__dict__)
21 print(F.name)
22 F.age = 100
23 del F.age
24 print(F.__dict__)
25 F.age = 1002
26 print(F.age)
反射内置attr应用

 

 

 

 

 


 
技术分享
 1 cmd_dict = {search:search,add:add,delete:delete,modify:modify}
 2 while True:
 3     count = 0
 4     for i in cmd_dict.keys():
 5         count += 1
 6         print("%s\t%s"%(count,i))
 7     opt = input("请输入选项>>> ")
 8     if not opt:continue
 9     if opt in cmd_dict:
10         func = cmd_dict.get(opt)
11         func()
菜单案例

 

python反射及其attr系列案例