在Python中,如何获得传递给我的decorator的带有参数的函数名?

在Python中,如何获得传递给我的decorator的带有参数的函数名?,python,methods,decorator,python-decorators,Python,Methods,Decorator,Python Decorators,我试图创建一个装饰器,它将验证参数是否存在,并检索被装饰的方法的名称 我可以在函数的第二层访问方法的名称,但不能访问第一层 例如,我有一个装饰师 def p_decorate(name, *a, **k): print(name + ' is at object: ') print a #I would like to get the method object here def fn(*a, **k) print a #object prints her

我试图创建一个装饰器,它将验证参数是否存在,并检索被装饰的方法的名称

我可以在函数的第二层访问方法的名称,但不能访问第一层

例如,我有一个装饰师

def p_decorate(name, *a, **k):
    print(name + ' is at object: ')
    print a #I would like to get the method object here
    def fn(*a, **k)
        print a #object prints here instead
    return fn
return p_decorate
我有这个班级我想装饰一下

class Person(object):
    @p_decorate('John')
    def get_fullnameobject(self):
        return self.name
我希望它能打印:

John is at object: (<function get_fullnameobject at 0x000000003745A588>,)
(<function get_fullnameobject at 0x000000003745A588>,)
John在object:(,)
(,)
但结果是:

John is at object: ()
(<function get_fullnameobject at 0x000000003745A588>,)
John在object:()
(,)

调用函数
p\u
时只使用参数
John
*a
**k
都将为空),因此
a
将得到一个空元组

需要注意的是,返回的
fn
callable之后将使用
get\u fullnameobject
callable调用


更重要的是,您当前的实现是不完整的,因为您永远无法调用该方法——您需要另一个闭包来实际执行该操作。

您需要另一个嵌套函数来定义接受参数的装饰器

def p_decorate(name):
    def _(f):
        print(name + ' is at object: ')
        print f
        def fn(*a, **k):
            # Do something, but ultimately you probably want to call f
            ...
        return fn
    return _
p\u decoration(“John”)
返回实际的decorator,它将
get\u fullnameobject
作为其
f
参数,并返回要绑定到
get\u fullnameobject
的新
fn
对象。如果没有decorator语法,用法如下

def get_fullnameobject(self):
    return self.name

get_fullnameobject = p_decorate("John")(get_fullnameobject)