python代码符号_Python的@符号

这篇博客介绍了Python中的装饰器使用,特别是@classmethod和@staticmethod。@classmethod用于创建类方法,需要一个cls参数;@staticmethod则类似全局函数,不与实例或类绑定。此外,还展示了装饰器如何修饰函数以及一个不常见用法,即用于实现单例模式。
摘要由CSDN通过智能技术生成

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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值