【发布时间】:2012-11-15 08:53:17
【问题描述】:
我正在尝试实现一个装饰器类,该类将装饰其他类中的方法。但是,我需要包含装饰器中可用的装饰方法的类。我似乎在任何地方都找不到它。
这是一个例子:
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
在装饰器类中,可调用对象是函数类型,而在类本身中,它是实例方法类型。我可以从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):
.
.
但我不想这样做,因为它是多余的而且不好。
或者我应该以其他方式实现它吗?我基本上需要装饰器的几个参数,并且我需要装饰器中的装饰方法的类。
【问题讨论】:
-
你什么时候需要上课?您可以将内部包装器修改为
def function_wrapper(self, *args, **kwargs),并获取类为self.__class__。如果您需要装饰器之外的类,那么正如 katrielalex 已经指出的那样,它要困难得多。
标签: python