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>
