Label (Space delimited): Reflection
This chapter focuses on the study of object-oriented reflection
When it comes to reflection, not the definition of reflection, let's consider a problem first:
If I have defined a class before, there is a class instantiation object, we can access the object's properties through the class;
Here we first define a class:
class People: def __init__(self,name,age): self.name=name self.age=age def talk(self): print('%s is talking' %self.name)obj=People('engon',18)print(obj.talk)#这里是属性print(obj.name) #obj.__dict__{'name'}
The above example illustrates: We have previously accessed properties, methods, and objects.
- If our program has interaction with the user, it requires the user to enter the attributes they want to access:
Look at the code below, right?
class People: def __init__(self,name,age): self.name=name self.age=age def talk(self): print('%s is talking' %self.name)obj=People('engon',18)choice=input('>>:')print(obj.choice)
The result of the above code execution is definitely not possible, because obj. must be the name of a property, not a string;
- The key now is that we're going to be able to map the attributes through the user's string:
Question: How to map an object property by string: (Here we need to learn several built-in methods)
1.hasattr ()
class People: def __init__(self,name,age): self.name=name self.age=age def talk(self): print('%s is talking' %self.name)obj=People('engon',18)print(hasattr(obj,'name'))#obj.name #obj.__dict__{'name'}print(hasattr(obj,talk))print(getattr(obj,'nameXXX',None))#获取print(getattr(obj,'talk',None))setattr(boj,'sex','male') #obj.sex='male'#设置模块print(obj.sex)delattr(obj,'age')#删除print(obj.__dict__)
Application of Reflection:
Through the code below we can call the property by receiving the user's input;
So that it can be mapped out;
Object-oriented Reflection