Reflection # operates on the members of an object in the form of a string (get/Find/Add/delete).
Built-in functions for operations:
1. Get GetAttr (object, name)
# to get the contents of name in Object
classFoo:def __init__(self, Name, age): Self.name=name Self.age=Ageobj= Foo ('Lemon147', 18) v= GetAttr (obj,'name')Print(v)>>>Lemon147add= GetAttr (obj,'Add','Not find!')#if the object obj has a property add then returns the value of Self.add, otherwise returns ' not find '!Print(ADD)>>> notfind!GetAttr
2. Find Hasattr (object, name)
# Check if the object has name
classFoo:def __init__(self, Name, age): Self.name=name Self.age=Ageobj= Foo ('Lemon147', 18) setattr (obj,'Add','123')Print(GetAttr (obj,'Add')) delattr (obj,'Add') Add= Hasattr (obj,'Add')Print(ADD)>>>falsehasattr
3. Add SetAttr (object, Name,value)
# set name to value in object
classFoo:def __init__(self, Name, age): Self.name=name Self.age=Ageobj= Foo ('Lemon147', 18) setattr (obj,'Add','123') Add= Hasattr (obj,'Add')Print(ADD)>>>TruePrint(GetAttr (obj,'Add')) >>>123SetAttr
4. Delete Delattr (object, name)
# Remove the Member from object ' name '
classFoo:def __init__(self, Name, age): Self.name=name Self.age=Ageobj= Foo ('Lemon147', 18) setattr (obj,'Add','123')Print(GetAttr (obj,'Add')) delattr (obj,'Add') Add= Hasattr (obj,'Add')Print(add)deaattr
Note: getattr,hasattr,setattr,delattr changes to the module are made in memory and do not affect the actual content in the file.
Application Scenarios
Dynamically invoke different modules or functions, depending on the input or selection. (Same as dictionary-dictionary through key, query corresponding value is similar.) )
def S1 (): return ' Home Page ' def S2 (): return ' News ' def S3 (): return ' Essence '
test002
ImportTest002foo=True whileFOO:INP= Input ('Please enter the content you want to query, enter ' Q ' to exit:')#enter ' s1 ' to perform ' home ' ifhasattr (test002, INP): v=getattr (test002, INP)Print(V ())elifINP = ='Q': Break Else: Print('wrong input')test001
Python Learning Notes __ Reflection