Python Learning notes-decorators and objects

Source: Internet
Author: User

1. __import__ of Reflection

We know that the import statement is for importing external modules, and of course from...import ... Yes, but actually import actually works using the BUILTIN function __import__.
In some programs, we can dynamically call the function, if we know the name of the module (string), we can easily use dynamic invocation.

__import__ (module_name[, globals[, locals[, FromList]]) #可选参数默认为globals (), locals (), []
__import__ (' OS ')
__import__ (' OS ', Globals (), locals (), [' Path ', ' Pip ']) #等价于from OS import path, Pip

Example: Importing a module as a string

MoD = __import__ (' sys ')
Print (Mod.path)

Example: Calling a function in a module as a string

func = getattr (mod, ' path ')
Print (func)

Example: Import a module from a package named Main, module named MoD

AA = __import__ (' Main.mod ')

AA = __import__ (' main ', globals={}, locals={}, fromlist=[' mod ')

AA = __import__ (' main ', Globals (), locals (), [' MoD '])

m = getattr (aa, ' mod ')
Print (M.first (' Kevin '))

n = getattr (M, ' first ')
Print (Type (n))
N (' Kevin ')

Note: The Web framework loads different modules according to different URLs and handles them differently.


2, the decorative device

The adorner's syntax begins with @, followed by the declaration of the function the adorner is decorating.
In fact, generally speaking, the adorner is actually a function, a function used to wrap the function, the adorner is called when the function declaration is completed, and the function declared after the call is replaced by a function that has been decorated by the adorner.

When the original function is a tangible parameter, the corresponding parameter func (args) is also needed in the function of decoration.

When the original function has return value, Returne func (args) must also be in the decorated function;

Adorners are divided into non-parametric decorations and ornamental:

★ Non-parametric decoration
Here's how to define it:
For example, first define a decoration method:

def deco (func):
"" "No parameter calls decorator declaration must have a parameter, this parameter will receive the method to be decorated" ""
Print (' first adorner ') #进行额外操作
return func #返回一个可调用对象 (This example returns a method as an input parameter), when a new function is returned, the new function can be a global method or an inline function of the decorator function, as long as the function's signature is the same as the decorated function

@deco
def MyFunc (args): Method of #应用 @deco modification
Print (' My first decorator ', args)

Return (' Nihao ', args)


MyFunc (' Wangkai ') #调用被装饰的函数
MyFunc (' Kevin ')

info = MyFunc (' Gonghui ')
Print (info)

Note: When defining a decorator method using the above method, the extra action in the function body executes only when the decorated function is first called;

If you want to make sure that the extra action is executed every time the decorated function is called, you need to change to the following notation:
def deco (func):
def replacefunc (args): #定义一个内嵌函数, this function wraps the decorated function and provides the code for the extra operation
Print (' first adorner ') #进行额外操作
return func (args) #产生对被装饰函数的调用
Return Replacefunc #由于返回的是这个新的内嵌函数, so make sure that each call to the extra operation runs

@deco
def MyFunc (args): Method of #应用 @deco modification
Print (' My first decorator ', args)
Return (' Nihao ', args)

MyFunc (' Wangkai ') #调用被装饰的函数
MyFunc (' Kevin ')
info = MyFunc (' Gonghui ')
Print (info)


★ decorated with:

def Decowithargs (ARG):
"" "because the decorator function with parameters only uses the parameters when applied and does not receive the decorated function as arguments,
Therefore, a decorator function must be returned, which encapsulates the decorated function ""
def Newdeco (func): #定义一个新的decorator函数
def replacefunc (args): #在decorator函数里面再定义一个内嵌函数, which encapsulates a specific operation
Print (' first adorner ') #进行额外操作
AA = func (args) #对被装饰函数进行调用

Print (' Goodbye ')

Return AA
Return Replacefunc
return Newdeco #返回一个新的decorator函数

@decoWithArgs ("demo")
def MyFunc (args): Method of #应用 @decoWithArgs modification
Print (' My first decorator ', args)
Return (' Nihao ', args)

MyFunc (' Wangkai ') #调用被装饰的函数
MyFunc (' Kevin ')
info = MyFunc (' Gonghui ')
Print (info)

When we apply an ornament method to a method, we actually change the entry point of the function code block referenced by the name of the decorated function, so that it points back to the function entry point returned by the adornment method. Thus we can use decorator to change the function of an existing function, add various operations, or completely change the original implementation.

This article is from the "Autumn Fairy tale" blog, please be sure to keep this source http://wushank.blog.51cto.com/3489095/1656952

Python Learning notes-decorators and objects

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.