Example of reflection usages in Python

Source: Internet
Author: User
This example describes the reflection usage in Python. Share to everyone for your reference. Specific as follows:

Import sys, types,newdef _get_mod (modulepath): Try:amod = Sys.modules[modulepath] If not isinstance (AMod, types.    Moduletype): Raise Keyerror except Keyerror: # The last ["] is very important! AMod = __import__ (Modulepath, Globals (), locals (), ["]) Sys.modules[modulepath] = AMod return amoddef _get_func (FULLF  UNCName): "" "Retrieve a function object from a full dotted-package name." "  # Parse out the path, module, and function Lastdot = Fullfuncname.rfind (U ".") FuncName = Fullfuncname[lastdot + 1:] Modpath = Fullfuncname[:lastdot] AMod = _get_mod (modpath) Afunc = GetAttr (AMod, F  UNCName) # Assert The function is a *callable* attribute. Assert callable (Afunc), U '%s is not callable. '% Fullfuncname # Return A reference to the function itself, # not the Res  Ults of the function.  Return afuncdef _get_class (FullClassName, Parentclass=none): "" "Load a module and retrieve a Class (not a instance). If the ParentClass is supplied, className must be of parEntclass or a subclass of ParentClass (or None is returned).  "" "AClass = _get_func (fullclassname) # Assert that the class is a subclass of ParentClass. If ParentClass is isn't none:if not Issubclass (AClass, ParentClass): Raise TypeError (U "%s was not a subclass of%s"  % (FullClassName, ParentClass)) # Return A reference to the class itself, not a instantiated object. Return aclassdef Applyfuc (obj,strfunc,arrargs): Objfunc = GetAttr (obj, strfunc) return apply (Objfunc,arrargs) def getobj ECT (fullclassname): Clazz = _get_class (fullclassname) return Clazz () if __name__== ' __main__ ': Aa=getobject (" Inetservices.services.company.Company ") bb=applyfuc (AA," select ", [' SELECT * from Ngsys2 ', None]) print BB

Hopefully this article will help you with Python programming.

  • 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.