美文网首页
Python中的类装饰器

Python中的类装饰器

作者: yeathMe | 来源:发表于2018-01-05 17:36 被阅读0次

1,对象能不能被调用

在Python中对象一般是不可以被调用的, person=Person() ,person() 这样调用person对象会出现错误。
如果在定义Person类的时候本身 给类定义了call 方法,那么对象就可以被调用,调用对象 的时候会执行类中定义的call方法。


class Person(object):
    def __init__(self,newName, newAge):

        self.name=newName
        self.age=newAge
    def __call__(self, *args, **kwargs):
        print "__call__"

person =Person("zhangsan","12")
person()//这里会执行__call__ 方法

2 使用类装饰方法


class Person(object):
    def __init__(self,func):

        print "__init__"
        print func
        self.__func=func
    def __call__(self, *args, **kwargs):
        self.__func(*args,**kwargs)
        print "__call__"

@Person
def test(name,age):
    print "test"
test("zhangsan",23)

上面代码中使用Person类来装饰test方法。
(1) 什么时候进行装饰?
当程序加载代码到@Person 的时候就会立即进行装饰,首先会创建一个Person对象, 将test函数作为init 方法的第二个参数,我们假定这个Person对象为per, 在init 方法中将func方法赋值给per的func属性, 装饰的结果就是test引用指向了per对象,所以当我们执行test("zhangsan",23)的时候实际上是在执行 call 方法, 在call方法中会执行func所引用方法,func所引用的方法正是原始test所指向的方法。

运行结果为:
init
<function test at 0x000000000383A438>
test
call

相关文章

网友评论

      本文标题:Python中的类装饰器

      本文链接:https://www.haomeiwen.com/subject/ggusnxtx.html