Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / Python的@符号

Python一直都属于用,没有去系统学习过,在一次代码review中见到了@符号,回来看了下,这个符号用于装饰器中,用于修饰一个函数,把被修饰的函数作为参数传递给装饰器,下面举几个例子:1. @classmethod和@staticmethod这两个含义很明显,在定义方法的时候@classmethod表示该方法是类方法,类方法必须有一个参数为cls,表示类本身,实例方法的第一个参数是self.@staticmethod修饰的方法基本上和一个全局函数相同。这两个修饰的方法通过实例和类调用都是可以的
class A():    @classmethod    def classM(cls):        print "class method, and invoker:",cls.__name__    @staticmethod    def staticM():        print "static method"class B(A):    pass A.classM()  #class method, and invoker: AB.classM()  #class method, and invoker: BA.staticM() #static methodB.staticM() #static methoda=A()a.classM()  #class method, and invoker: Aa.staticM() #static methodb=B()b.classM()  #class method, and invoker: Bb.staticM() #static method2. 作为普通的修饰符,下面的定义类似于 testone=func(testone) 
class C():    def func(fn):        def test(*args):            print "hello"        return test    @func    def testone(a,b):        print a**2+b**2    if __name__=="__main__":        testone(3,4)  #output:hello   
123456789101112131415
class C():    def func(fn):        def test(*args):            print "hello"            fn(*args)        return test    @func    def testone(a,b):        print a**2+b**2    if __name__=="__main__":        testone(3,4) #output:hello253. 不常见的写法,用来修饰一个class,在单例模式中能用到
def singleton(cls):    instance={}    def getinstance():        if cls not in instance:            instance[cls]=cls()        return instance[cls]    return getinstance @singletonclass Myclass:    pass #output>>> my1=Myclass()>>> print my1<__main__.Myclass instance at 0x00000000028C2F48>>>> my2=Myclass()>>> print my2<__main__.Myclass instance at 0x00000000028C2F48>--------------------------------------分割线 --------------------------------------CentOS上源码安装Python3.4  http://www.linuxidc.com/Linux/2015-01/111870.htm《Python核心编程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码] http://www.linuxidc.com/Linux/2013-11/92693.htmPython脚本获取Linux系统信息 http://www.linuxidc.com/Linux/2013-08/88531.htm在Ubuntu下用Python搭建桌面算法交易研究环境 http://www.linuxidc.com/Linux/2013-11/92534.htmPython 语言的发展简史 http://www.linuxidc.com/Linux/2014-09/107206.htmPython 的详细介绍:请点这里
Python 的下载地址:请点这里 本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-03/115107.htm