繁体   English   中英

如何在Python中查找装饰方法的包含类

[英]How to find the containing class of a decorated method in Python

我正在尝试实现一个装饰器类,它将装饰其他类中的方法。 但是,我需要在装饰器中保存装饰方法的类。 我似乎无法在任何地方找到它。

这是一个例子:

class my_decorator(object):

  def __init__(self, arg1, arg2):
    print(self.__class__.__name__ + ".__init__")
    self.arg1 = arg1
    self.arg2 = arg2

  def __call__(self, my_callable):
    print(self.__class__.__name__ + ".__call__")
    print(type(my_callable))
    self.my_callable = my_callable
#    self.my_callable_method_class = ?where to get this?

    def function_wrapper(*args, **kwargs):
      print(self.__class__.__name__ + ".function_wrapper")
      print(self.arg1)
      self.my_callable.__call__(*args, **kwargs)
      print(self.arg2)

    return function_wrapper


class MyClass(object):

  @my_decorator(arg1="one", arg2="two")
  def decorated_method(self):
    print(self.__class__.__name__ + ".decorated_method")
    print(type(self.decorated_method))
    print("hello")


m = MyClass()
m.decorated_method()

这将打印出来:

my_decorator.__init__
my_decorator.__call__
<type 'function'>
my_decorator.function_wrapper
one
MyClass.decorated_method
<type 'instancemethod'>
hello
two

在decorator类中,callable的类型为function,而在类本身内,它的类型为instancemethod。 我可以从instancemethod获取im_class,但是函数中没有这样的东西。

如何从装饰器中获取包含装饰方法的类?

我能做到这一点:

class my_decorator(object):

  def __init__(self, cls, arg1, arg2):

.
.

class MyClass(object):

  @my_decorator(cls=MyClass, arg1="one", arg2="two")
  def decorated_method(self):

.
.

但我不想这样做,因为它多余而且不好。

或者我应该以其他方式实现这一点? 我基本上需要一些装饰器的参数,我需要装饰器中的装饰方法的类。

你可以装饰这个

@decorate
class MyClass(object):

  @my_decorator(arg1="one", arg2="two")
  def decorated_method(self):

并使用外部装饰器将类参数发送到内部。


您的提案都不起作用,因为它们需要在类存在之前访问该类。 定义类时,首先在其主体内部执行代码(定义函数等),然后将结果范围分配给类__dict__ 所以在定义decorated_methodMyClass还不存在。

这是一个有效的修订版本。

# This holds all called method_decorators
global_method_decorator_list = []

class class_decorator(object):
  def __init__(self, arg1, arg2):
    print(self.__class__.__name__ + ".__init__")
    self.arg1 = arg1
    self.arg2 = arg2

  def __call__(self, my_class):
    print(self.__class__.__name__ + ".__call__")
    print(repr(my_class))
    print(my_class.__name__)
    self.cls = my_class
    class_decorators[my_class] = self
    self.my_class = my_class

    # Call each method decorator's second_init()
    for d in global_method_decorator_list:
      d._method_decorator_.second_init(self, my_class)

    def wrapper(*args, **kwargs):
      print(self.__class__.__name__ + ".wrapper")
      print(self.arg1)
      retval = self.my_class.__call__(*args, **kwargs)
      print(self.arg2)
      return retval

    return wrapper


class method_decorator(object):
  def __init__(self, arg1, arg2):
    print(self.__class__.__name__ + ".__init__")
    self.arg1 = arg1
    self.arg2 = arg2

  def __call__(self, my_callable):
    print(self.__class__.__name__ + ".__call__")
    print(repr(my_callable))
    self.my_callable = my_callable

    # Mark the callable and add to global list
    my_callable._method_decorator_ = self
    global_method_decorator_list.append(my_callable)

    def wrapper(*args, **kwargs):
      print(self.__class__.__name__ + ".wrapper")
      print(self.arg1)
      retval=self.my_callable.__call__(*args, **kwargs)
      print(self.arg2)
      return retval

    return wrapper

  def second_init(self, the_class_decorator, the_class):
    print(self.__class__.__name__ + ".second_init")
    print("The Class: " + repr(the_class))**


@class_decorator(arg1="One", arg2="Two")
class MyClass(object):

  @method_decorator(arg1="one", arg2="two")
  def decorated_method(self):
    print(self.__class__.__name__ + ".decorated_method")
    print(type(self.decorated_method))
    print("hello")


m = MyClass()
m.decorated_method()

输出如下所示:

class_decorator.__init__
method_decorator.__init__
method_decorator.__call__
<function decorated_method at 0x3063500>
class_decorator.__call__
<class '__main__.MyClass'>
MyClass
method_decorator.second_init
The Class: <class '__main__.MyClass'>
class_decorator.wrapper
One
Two
method_decorator.wrapper
one
MyClass.decorated_method
<type 'instancemethod'>
hello
two

不同的是,现在有一个单独的装饰器。 类装饰器的call ()将调用每个方法装饰器“second_init()”方法,并将类传递给那里。

有趣的是,method_decorator的call ()将在class_decorator之前调用。

如果您使装饰器返回的对象成为描述符 ,那么您可以挂钩属性查找以返回链接方法和类(或实例)的其他对象。

对于方法样式描述符,您只需要实现__get__方法。 在类上查找方法时,以下两个是等效的:

m = MyClass.decorated_method
# It will actually get the object from any parent class too.  But this will do for a simple example
m = MyClass.__dict__['decorated_method'].__get__(MyClass)

例如,以下内容是等效的:

instance = MyClass()
m = instance.decorated_method
m = type(instance).__dict__['decorated_method'].__get__(instance, type(instance))

所以表达式instance.decorated_method(...)实际上调用了__get__方法返回的对象。 这是允许简单函数对象转换为添加隐式self参数的绑定方法对象的相同过程。

创建此可调用对象时,您应该拥有所需的所有信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM