# the functions and methods obtained by using reflection can be called directly with parentheses as usual, and the instance can be constructed directly after obtaining the class.
# However, the obtained field cannot be assigned directly because it is actually another reference to the same place, and the assignment can only change when
# before this quote.
#I. Accessing the properties of an objectclassPerson ():def __init__(self): Self.name='Mic'Self.age= 18defrun ():Print('Run----') obj=Person ()Print(dir (obj))ifHasattr (obj,'name'): SetAttr (obj,'name','Merry')Print(GetAttr (obj,'name'))#1.dir (obj) returns a list containing most of the property names of obj#2.hasattr (obj, attr) determines whether an object contains a specified property#3.getattr (obj, attr) Gets the value of the specified property of the object#4.setattr (obj, attr, value) sets the value of the specified property for the object#two. Accessing the metadata of an object#the Dir () method returns a property that contains some metadata that is not defined by itself;#The types module defines all Python built-in types;#the Isinstance () function can also check whether the object specifies the data type;#1. The metadata of the reflection moduleImportRePrint(Re.__doc__)#Document StringPrint(Re.__name__)#module name in string formPrint(Re.__file__)#print (re.__dict__) # returns the property name and properties of the object as a dictionary;#in Python3, the dictionary's items () method returns a class with a built-in __iter__ () method.#Therefore, is an iterative object, can be used for loop traversal, but not by subscript to fetch;#in Python2, the dictionary's items () method returns [(,), (,), (,)] type data;#2. Reflection class meta-dataPrint(person.__doc__)#Document StringPrint(person.__name__)#the name of the class when definedPrint(person.__module__)#module name in string formPrint(person.__bases__)#tuple of the first level parent classPrint(person.__dict__)#Property Name-Property dictionary#3. Reflection Instance MetadataPrint(obj.__dict__)#Property Name-Property dictionaryPrint(obj.__class__)#the class object for the instancePrint(obj.__class__==person)#True#4. Reflection of the metadata of the built-in functions and methods#Python's built-in function is a C-written module that can be the builtin_module_names field of the SYS module#View all built-in modulesPrint(max.__doc__. Splitlines () [0])#function DocumentPrint(max.__name__)#name when the function is definedPrint(max.__self__)#The class that points to the methodPrint(max.__module__)#The module name where the function resides# ... Slightly#the Inspect module provides a series of functions to help reflect queries;
Reflection | Python