One, reflectionVariables in reflection classVariables in reflection objectsVariables in reflection moduleReflect variables in this document1、Definition: use the variable name of string data type to get the value of this variable.For example:Name= 'xiaoming' print(name) # xiaoming print('name') # name Usually we want to get'xiaoming'This value is to be obtained by name, but if you want to use a string'name' Get this value?Reflection is needed.2、The scene of reflection application is to convert the received string to the name of the variable.1,input If the user input is a, then print 1, if the input is b, print 2, if the input is name, print Xiaoming2,fileThe string read from the file is converted to the name of the variable.3,networkConverts the string transferred from the network to the name of the variable.
3、Variables in reflection class: static attributes, class methods, static methodsclass Foo: School = 'Zhbit' Country = 'China' language = 'Chiness' @classmethod def class_method(cls): print('in class_method') @staticmethod def static_method(): print('in staticmethod') def hahaha(self): print('hahaha') # If the input School is to be printed, the corresponding value is printed. Country also prints the corresponding value.Be1,By judgement:InP= input('Please enter:') if inp == 'School':print(Foo.School) elif inp == 'Country':print(Foo.Country) elif inp == 'language':print(Foo.language) # It's OK to write this when there are fewer attributes, but think about it, if there are 100 attributes, would you write 100 judgments?So please look at the reflection.Be2,Reflection implementationwhile True: inp = input('>>>') print(getattr(Foo,inp)) # OK,This is achieved, and no matter how many attributes can be achieved, it is very simple.Then we will analyze the method of reflection.2-1getattrMethodUsage: getattr (variable name (namespace), string (belonging to variable name in a namespace)).Get static attributesPrint (getattr (Foo),'School')) # That's Foo.School.Print (getattr (Foo),'class_method')) # It means Foo.class_method gets a function address.Print (getattr (Foo),'static_method')) #It means Foo.static_method gets a function address.If you want to perform this function,Getattr (Foo,'class_method')() # in class_method getattr(Foo,'static_method')() # in staticmethod 2-2hasattrMethodIf # does not have this property or method, it will report an error, and for security reasons, you need to determine if there is such a property or method to executeWe need to use hasattr ().Print (hasattr (Foo),'class_method')) #True print(hasattr(Foo,'hello')) # False while True: inp = input('Please enter:') if hasattr(Foo,inp): print(getattr(Foo,inp)) 4、Reflection object attribute, common methodclass Foo: def __init__(self,name,age): self.name = name self.age = age def sleep(self): print('%sSleep, kill him quickly.' %self.name) xiaobai = Foo('Small white',12) print(getattr(xiaobai,'name')) getattr(xiaobai,'sleep')() 5、Variables in reflection moduleImport OS OS is a module.Os.rename ('a.txt','a.bak') getattr(os,'rename')('a.bak','a.txt') 6、Reflect variables in this documentA= 1 b = 2 age = 18 # functionDef func ():Print (666) # classclass A:pass import sys print(sys.modules['__main__']) # Namespace of this documentPrint (sys.modules[)'__main__'].a) # The value of the a variable in the namespace of this document:1 print(sys.modules['__main__'].func) # The address of function func in the namespace of this document: < function func at0x000001C735B81E18> print(sys.modules['__main__'].A) # The address of class A in the namespace of this document: <class '__main__.A'> # __name__ and'__main__' Same, representing the namespace of this document.Print (sys.modules[)'__main__']) print(sys.modules[__name__]) # reflexPrint (getattr (sys.modules[__name__]),'a')) # 1 print(getattr(sys.modules['__main__'],'a')) # 1 print(getattr(sys.modules[__name__],'age')) # 18 getattr(sys.modules[__name__],'func')() #Execution function func:666 obj = getattr(sys.modules[__name__],'A')() #Instantiated objectPrint (obj)7、setattr:Increase and changeThe classclass Foo: country = 'China' # functionDef func ():Print (666) print(getattr(Foo,'country')) # China setattr(Foo,'country','Big China') # Accept three parameters: namespace.'Variable name' Variable valuePrint (getattr (Foo),'country')) # Big China setattr(Foo,'fun',func) # Add an attribute fun to the class Foo, which is the address of the func function.Print (func)<function func at 0x00000188B34F2D08> print(Foo.fun) # <function func at 0x0000026DC4A21E18> getattr(Foo,'fun')() # 666 8、delattr:Deleteclass Foo: language = 'Leetspeak' country = 'China' def func(): print(666) print(Foo.__dict__) delattr(Foo,'language') print(Foo.__dict__) Two, built-in methods __str__ and __repr__1、Definition of built in methodWithout programmer definition, the method in the class itself is built-in method.It does not need to be called directly, and triggers automatically when encountering specific scenarios.The built-in methods are usually long:Can be called: double down method, magic.Method and built-in methodFor example, we are familiar with the initialization function __init__ (), which is built in.Automatically execute when instantiating objects.2、__str__And __repr____str__When you print an object, print (obj) triggers __str__.When you use it%sThe output object of formatted time is print.'%s' %obj) Trigger __str__When STR turns data type strongly, str (obj) triggers __str__.__repr__Repr is STR's spare tire.Print the object directly, execute __str__ when __str__ has run, and do not print.Str__, execute __repr__When you use it%rOutput object time print ('%r' %obj) Trigger __repr__When repr turns data type strongly, repr (obj) triggers __repr__.Note: both __str__ and __perp__ must use return, and the returned value must be a string.Example: class Fruit: def __init__(self,name,price): self.name = name self.price = price def __str__(self): return 'in str:%sThe price is:%s' %(self.name,self.price) def __repr__(self): return 'in repr:%sThe price is:%s' % (self.name, self.price) apple = Fruit('Apple',5) # Print objects directly, execute __str__ on __str__, and execute __repr__ when no __str__ is available.Print (Apple)in str:The price of apples is:5 # When you use it%sThe output object of formatted time is print.'%s' %obj) Trigger __str__Print ('%s' %apple) # in str:The price of apples is:5 # When you use it%rOutput object time print ('%r' %obj) Trigger __repr__Print ('%r' %apple) # in repr:The price of apples is:5 # strStr (obj) triggers __str__ when the data type is strongly converted.Print (STR (Apple))in str:The price of apples is:5 # reprRepr (obj) triggers __repr__ when the data type is strongly converted.Print (repr (Apple))in repr:The price of apples is:5 Upgrade:class Fruit: def __str__(self): return 'Fruit_str' def __repr__(self): return 'Fruit_repr' class Apple(Fruit): def __str__(self): return 'Apple_str' def __repr__(self): return 'Apple_repr' apple = Apple() print(apple) # appleIt's an apple class object. Print it directly. Find it from the apple class first. Execute apple's STR when STR is present, and no STR is present.If you look for __str__ from the parent class, the parent class executes it. If the parent class is not, then find the subclass.__repr__ has __repr__ for executing subclasses, but no parent class.The parent class does not print the object space address.