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
?
?
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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>
--------------------------------------分割线 --------------------------------------