zoukankan      html  css  js  c++  java
  • @ python的修饰符

    @符号在python语言中具有特殊含义,用来作为修饰符使用。
    具体可以参考下面的代码:

    #! /usr/bin/env python
    #
    coding=utf-8

    from time import ctime, sleep

    def tcfunc(func):
        
    def wrappedFunc():
            
    print '[%s] %s() called' %(
                ctime(), func)
            
    return func()
        
    print "in tcfunc called"
        
    print "wrapped func %s" %wrappedFunc
        
    return wrappedFunc

    # decorator 仅调用tcfunc函数,该函数将foo作为一个参数,返回一个
    #
     wrappedFunc函数对象,用该对象来取代foo函数在外部的调用,foo
    #
     定义的函数只能够在内部进行调用,外部无法获取其调用方式!!
    @tcfunc         # call sequence is : tcfunc(func) --> wrappedFunc -- > func
    def foo():
        
    print "in foo called"
        
    pass

    print "foo func : %s" %foo

    foo()  
    print "-"*100
    sleep(
    4)

    for i in range(2):
        sleep(i)
        foo()
        
    print "-"*100

    上面函数中,tcfunc定义了一个函数,里面内嵌一个函数,该函数需要一个func的参数。

    @tcfunc则表示下面定义的函数将函数名作为tcfunc的参数被tcfunc调用。
    代码:
    @tcfunc
    def foo():
        
    pass

    在定义的时候,就被tcfunc调用,即tcfunc(foo),该函数返回一个wrappedFunc对象,而该定义foo函数名对象其实已经被wrappedFunc对象给取代, foo()定义的函数只在tcfunc函数内部作为参数被使用!我们可以通过打印它们的地址来查看tcfunc外部调用的foo与wrappedFunc是否为同一个对象:

    in tcfunc called
    wrapped func <function wrappedFunc at 0x01A3DD30>
    foo func : <function wrappedFunc at 0x01A3DD30>
    [Thu Jan 08 00:04:35 2009] <function foo at 0x01A3DCF0>() called
    in foo called
    ----------------------------------------------------------------------------------------------------
    [Thu Jan 08 00:04:39 2009] <function foo at 0x01A3DCF0>() called
    in foo called
    ----------------------------------------------------------------------------------------------------
    [Thu Jan 08 00:04:40 2009] <function foo at 0x01A3DCF0>() called
    in foo called
    ----------------------------------------------------------------------------------------------------

    从中可以看到,在tcfunc外部的函数对象与wrappedFunc的函数对象是同一个对象,在tcfunc内部参数func中调用的
    才是实际定义的foo函数对象!!!

  • 相关阅读:
    Stock Transfer I
    Negative Stock in "Stock in Transit"
    ZFINDEXITS
    Plan Driven Procurement III: Classic Scenario in SRM 5.0
    C++builder 创建进程之CreateProcess函数
    常用DOS命令
    【转】程序员的几个级别
    几本书
    OOP SOLID原则
    SSRS 使用总结
  • 原文地址:https://www.cnblogs.com/ubunoon/p/decorate_python.html
Copyright © 2011-2022 走看看