下面是一个无用的示例,说明我没有设法用my_decorator来修饰我的my_decorator函数,并给出了一些额外的参数:
def my_decorator(fn=None, message=None, **options):
assert fn is not None, 'fn is not found'
print('function is found')
print(message)
return fn
# This syntax works (but does not make sense...)
@my_decor
已更新:问题下方内联回答
我有一个检查程序,其中一个目标是让装饰器中的逻辑知道它正在装饰器中的函数是类、方法还是常规函数。这以一种奇怪的方式失败了。以下是在Python 2.6中运行的代码:
def decorate(f):
print 'decorator thinks function is', f
return f
class Test(object):
@decorate
def test_call(self):
pass
if __name__ == '__main__':
Test().te
在Python中,如何在不调用函数的情况下获得字符串形式的函数名?
def my_function():
pass
print get_function_name_as_string(my_function) # my_function is not in quotes
应输出"my_function"。
Python中有这样的函数吗?如果没有,有没有关于如何用Python语言实现get_function_name_as_string的想法?
考虑以下代码:
class MyCustomDescriptor:
def __init__(self,foo):
self._foo = foo
def __call__(self,decorated_method):
# Here's my question... Is there any way to get a reference to the
# type (ClassA or ClassB) here?
return self
def __get__(self,instance,t
我想在Python代码库中添加一些有用的日志记录。
我希望添加表格中的日志记录:
[2022-01-06 10:00:01] function foo called with args x=1, y=22, z=3
[2022-01-06 10:00:05] function foo returned 1416
[2022-01-06 10:00:13] function bar called with args w=1416
[2022-01-06 10:00:16] function bar returned None
我可以通过用一个装饰符将所有函数包装在代码库中来实现这一点,但是有更好
我有一个请求处理程序和一个装饰器,我想使用装饰器中的self对象。
class MyHandler(webapp.RequestHandler):
@myDecorator
def get(self):
#code
更新:请注意第一次和第二次自我之间的区别
class myDecorator(object):
def __init__(self, f):
self.f = f
def __call__(self):
#work with self
MyHandler > get (函
我想用相同的包装器在Python中包装一些类方法。
从概念上讲,在最简单的场景中,它看起来像这样:
x = 0 # some arbitrary context
class Base(object):
def a(self):
print "a x: %s" % x
def b(self):
print "b x: %s" % x
class MixinWithX(Base):
"""Wrap"""
def a(self):
为了理解python中的条件修饰器,我遇到了。该问题的公认答案解释了如何定义条件装饰符,而不是如何使用它。
示例代码如下:
class conditional_decorator(object):
def __init__(self, dec, condition):
self.decorator = dec
self.condition = condition
def __call__(self, func):
if not self.condition:
# Return the function u