栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

带有参数并访问类实例的Python Decorator [重复]

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

带有参数并访问类实例的Python Decorator [重复]

是。实际上,按照您的意思,实际上没有一种方法可以编写 没有
访问权限的装饰器

self
。装饰的函数包装了原始函数,因此它必须至少接受该函数接受的参数(或可以从中导出这些参数的某些参数),否则它将无法将正确的参数传递给基础函数。

为此,您不需要执行任何特殊操作,只需编写一个普通的装饰器即可:

def deco(func):    def wrapper(self, *args, **kwargs):        print "I am the decorator, I know that self is", self, "and I can do whatever I want with it!"        print "I also got other args:", args, kwargs        func(self)    return wrapperclass Foo(object):    @deco    def meth(self):        print "I am the method, my self is", self

然后,您可以使用它:

>>> f = Foo()>>> f.meth()I am the decorator, I know that self is <__main__.Foo object at 0x0000000002BCBE80> and I can do whatever I want with it!I also got other args: () {}I am the method, my self is <__main__.Foo object at 0x0000000002BCBE80>>>> f.meth('blah', stuff='crud')I am the decorator, I know that self is <__main__.Foo object at 0x0000000002BCBE80> and I can do whatever I want with it!I also got other args: (u'blah',) {'stuff': u'crud'}I am the method, my self is <__main__.Foo object at 0x0000000002BCBE80>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/669657.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号