zoukankan      html  css  js  c++  java
  • 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: A
    B.classM()  #class method, and invoker: B
    A.staticM() #static method
    B.staticM() #static method
    a=A()
    a.classM()  #class method, and invoker: A
    a.staticM() #static method
    b=B()
    b.classM()  #class method, and invoker: B
    b.staticM() #static method
    

     

    2. 作为普通的修饰符,下面的定义类似于 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
    
    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:
    hello
    25
    

    3. 不常见的写法,用来修饰一个class,在单例模式中能用到

    def singleton(cls):
        instance={}
        def getinstance():
            if cls not in instance:
                instance[cls]=cls()
            return instance[cls]
        return getinstance
    
    @singleton
    class Myclass:
        pass
    
    #output
    >>> my1=Myclass()
    >>> print my1
    <__main__.Myclass instance at 0x00000000028C2F48>
    >>> my2=Myclass()
    >>> print my2
    <__main__.Myclass instance at 0x00000000028C2F48>
    

      

      

  • 相关阅读:
    wpf passwordbox控件 光标移到最后
    C#程序 给IE网页IFRAME控件中所嵌入网页的元素赋值
    C#客户端填充外部IE浏览器中网页文本(input)且不提交
    C# 获取当前网页HTML
    WPF 带有提示文本的透明文本框
    C# 导出Excel文件 所导出文件打开时提示“Excel文件格式与扩展名指定格式不一致”
    php生成验证码
    Python命名规范
    UE4碰撞规则详解
    四大编程思想简述
  • 原文地址:https://www.cnblogs.com/baibai-tech/p/4035488.html
Copyright © 2011-2022 走看看