我想實現一個裝飾器類,它將裝飾其他類中的方法。但是,我需要在裝飾器中保存裝飾方法的類。我似乎無法在任何地方找到它。如何在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
在裝飾類的調用是類型的函數,而類本身裏面的類型是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):
.
.
但我不喜歡這樣做,因爲它是多餘的,而不是漂亮的。
或者我應該用其他方式來實現嗎?我基本上需要一些裝飾器的參數,我需要裝飾器中的裝飾方法的類。
你到底什麼時候需要班級?您可以將內部包裝修改爲'def function_wrapper(self,* args,** kwargs)'並將該類作爲'self .__ class__'獲得。如果你需要修飾者以外的課程,那麼katrielalex已經指出了它的難度。 – Bakuriu