# Reflection : Used the form of string to manipulate object members (python Everything is an object , So you can also manipulate classes , modular ) """ 1、getattr(obj, str), Go to obj Object acquisition str attribute , Get the members of the object in the form of a string ( Field , Method ) 2、hasattr(obj, str) testing obj Is there any str member , Return value True or False 3、setattr(obj, key, value), Set up obj Object members ,key=value 4、delattr(obj, str) Delete obj Object members """ # Example 1. Operation example object class Foo1: def __init__(self, name, age): self.name = name self.age = age def bar(self): return self.name foo1 = Foo1('abc', '18') # We can go through getattr To take a value ,getattr(foo1, b) Indicates that I want to take variables from the object b Value (name) Corresponding field # This enables a simple interaction , Through the information entered by the user , Find object fields b = 'name' print(getattr(foo1, b)) inp = input(' Please enter the fields to query :') # You need to enter the object member name , If there is no such member, an error will be reported , Use try Capture exception try: print(getattr(foo1, inp)) except Exception as e: print(' The object you are looking for does not exist ') # adopt getattr Take out the object method fun = getattr(foo1, 'bar') print(fun()) # adopt hasattr Determine whether the member exists in the object , return true perhaps False print(hasattr(foo1, 'name')) print(hasattr(foo1, 'abc')) # By setting object members setattr(foo1, 'abc', '123') # print(foo1.abc) # adopt delattr Delete object members , An error will be reported when the value is deleted , adopt try Handling exceptions delattr(foo1, 'name') try: print(foo1.name) except Exception as e: print(e) # Example 2、 Operation class class Foo2: name = 'abc' age = '18' pass # Value print(getattr(Foo2, 'name')) # Judge whether it exists print(hasattr(Foo2, 'name')) print(hasattr(Foo2, 'abc')) # Set up setattr(Foo2, 'abc', '123') print(Foo2.abc) # Delete , An error will be reported when the value is deleted , adopt try Handling exceptions delattr(Foo2, 'name') try: print(Foo2.name) except Exception as e: print(e)