I. Reflections
What is reflection
The concept of reflection, first proposed by Smith in 1982, is a capability (introspection) that a program can access, detect, and modify its own state or behavior. The proposal of this concept soon triggered the research on the application of reflectivity in Computer science field. It is first used in the field of programming language design, and has achieved achievements in Lisp and object-oriented.
Reflection is the use of variable names of string data types to access variables.
Methods that apply to classes and objects in reflection:
GetAttr
Sttattr
Hasattr
Delattr
classfoo:f='Static variables of the class' def __init__(self,name,age): Self.name=name Self.age= AgedefSay_hi (self):Print('hi,%s'%self.name) obj=foo ('Egon', 73)Print(Hasattr (obj,'name'))#detect if a property is includedPrint(Hasattr (obj,'Say_hi'))#detect if a property is includedN=getattr (obj,'name')#Get PropertiesPrint(n) Func=getattr (obj,'Say_hi')#Get Propertiesfunc ()Print(GetAttr (obj,'aaaaaaaa','It doesn't exist.'))#Errorsetattr (obj,'SB', True)##设置属性SetAttr (obj,'Show_name',Lambdaself:self.name+'SB')##设置属性Print(obj.__dict__)Print(Obj.show_name (obj)) delattr (obj,' Age')## Delete PropertiesDelattr (obj,'Show_name')## Delete PropertiesDelattr (obj,'show_name111')#does not exist, then an errorPrint(obj.__dict__)
Class is also an object
classFoo (object): Staticfield=" old boy" def __init__(self): Self.name='Wupeiqi' deffunc (self):return 'func'@staticmethod#Static Methods defBar ():return 'Bar'Print(GetAttr (Foo,'Staticfield'))Print(GetAttr (Foo,'func'))Print(GetAttr (Foo,'Bar'))
Reflect current Module
You can also import other modules and use reflection to find out if there is a method for that module.
ImportSYSdefS1 ():Print('S1')defS2 ():Print('S2') This_module= sys.modules['__main__']#__main__ indicates that the current filePrint(Hasattr (This_module,'S1'))#determine if ' s1 ' is in the method name of the current fileGetAttr (This_module,'S2')()#removed
Python Face Object (reflection, built-in method)