Python ———— Reflection mechanism

Source: Internet
Author: User

The reflection functionality in Python is provided by the following four built-in functions: Hasattr, GetAttr, SetAttr, delattr, and four functions for internal execution of objects: Check for a member, get a member, set a member, delete a member.

#commons.py Filename="Nick" defF1 ():return "This is F1." defF2 ():return "This is F2." defnb ():return "This is niubily."   #index.py FileImportCommons#to look for something in a module based on a string.Target_func = GetAttr (Commons,"F1")#Find a functionresult =Target_func ()Print(Result) Target_func= GetAttr (Commons,"name")#Find Global VariablesPrint(target_func) Target_func= GetAttr (Commons," Age", None)#no returned none foundPrint(Target_func)#to determine whether something exists in a module based on a stringTarhas_func = Hasattr (Commons,"f5")#Find a functionPrint("Before:", Tarhas_func)#Tarhas_func = Hasattr (commons, "name") # Find global Variables#print (Tarhas_func) #to set something in a module as a stringSetAttr (Commons,"f5","Lambda x:return \ "This is new func.\"")#set a functionSetAttr (Commons," Age", 18)#Setting Global VariablesTarhas_func= Hasattr (Commons,"f5")#Check if a function existsPrint("After :", Tarhas_func)#to remove something from a module in the form of a stringDelattr (Commons,"f5")#Delete a functionTarhas_func= Hasattr (Commons,"f5")#Check if a function existsPrint("End:", Tarhas_func)

Object instance

classFoo:def __init__(self,name,age): Self.name=name Self.age= AgedefShow (self):Print("gets the method of the function") obj=foo ('2018 World Cup', 2018) #hasattr whether a field existsPrint(Hasattr (obj,'name'))#GetAttr getting InformationGetname=getattr (obj,'name')Print(GetName)#setattr Assignment ValueSetAttr (obj,' Time','2018-6-16')Print(obj.time)#delattr DeleteDelattr (obj,'name')Print(Obj.name)#error attributeerror after deletion: ' Foo ' object has no attribute ' name '

Python ———— Reflection mechanism

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.