First, what is reflected
It is reflected to the operation by the object class or string property
Is acquired by a string, setting, deleting object property or method
Second, how to use reflection
- Essentially reflected in the use of built-in functions, wherein the reflector has four built-in functions:
- hasattr: determining whether there is a method of the class
- getattr: to acquire memory address corresponding to the method according to the string in the object obj, added "()" to perform the brackets
- setattr: setattr the outside by a function bound to the instance
- delattr: Delete a class or instance method
class Foo:
def __init__(self,name,pwd):
self.name = name
self.pwd = pwd
def run(self):
print('run')
def speak(self):
print('speak')
p=Foo('xichen',18)
hasattr: determining whether there is a method of the class
print(hasattr(p,'name'))
True
getattr: to acquire memory address corresponding to the method according to the string in the object obj, added "()" to perform the brackets
if hasattr(p,cmd): run=getattr(p,cmd) run() else: print('该命令不存在')
Please enter the command: run
run
setattr: setattr the outside by a function bound to the instance
1.通过用户输入将外部的属性添加到当前的实例中 print(p.__dict__) key=input('请输入key:') value=input('输入value:') setattr(p,key,value) print(p.__dict__)
{ 'name': 'xichen' , 'pwd': 18}
Enter key: age
input value: 18 is
{ 'name': 'xichen', 'pwd': 18 is, 'Age': '18 is'}2.动态的将外部的方法添加到当前的实例中 def test(a): print(a) print(p.__dict__) setattr(p,'test',test) print(p.__dict__) p.test(0)
{'name': 'xichen', 'pwd': 18}
{'name': 'xichen', 'pwd': 18, 'test': <function test at 0x000001D1E98069D8>}
0delattr: Delete a class or instance method
1.最原始的删除对象的属性方法 print(p.__dict__) del p.name print(p.__dict__)
{'name': 'xichen', 'pwd': 18}
{'pwd': 18}2.动态删除p中属性为变量a的属性 a=input('请输入要删除的属性:') print(p.__dict__) delattr(p,a) print(p.__dict__)
Enter the property to delete: pwd # Remove object attributes are attributes pwd string
{ 'name': 'xichen', 'pwd': 18 is}
{ 'name': 'xichen'}
Third, an example of using reflection
Determine what object there is no property that I entered, and if so, print
cmd=input('请输入要查询的属性:') if hasattr(p,cmd): a=getattr(p,cmd) print(a) else: print('该属性不存在')
Please enter a query attributes: name
xichen