こんにちは、django.utils.decorators method_decorator デコレータを理解しようとしています。method_decorator は、関数デコレーターをクラス メソッド デコレーターに変えます。
このデコレーターのソースは (https://github.com/django/django/blob/master/django/utils/decorators.py) にあります。
私の関数デコレーターの例:
def run_eight_times(myfunc):
def inner_func(*args, **kwargs):
for i in range(8):
myfunc(*args, **kwargs)
return inner_func
私の基本クラスの例:
class Myclass(object):
def __init__(self,name,favorite_dish):
self.name = name
self.favorite_dish = favorite_dish
def undecorated_function(self):
print "%s likes spam in his favorite dish %s" % (self.name,self.favorite_dish)
ここで、django.utils.decorators method_decorator を使用して Myclass メソッド undecorated_function を装飾する継承クラスを作成したいと考えています。method_decorator を機能させるには、継承されたクラスで関数を再定義する必要があります。
だからこれはうまくいきます:
class Myrepetitiveclass(Myclass):
def __init__(self,*args, **kwds):
Myclass.__init__(self,*args,**kwds)
@method_decorator(run_eight_times)
def undecorated_function(self):
print "%s likes spam in his favorite dish %s" % (self.name,self.favorite_dish)
noisier_me = Myrepetitiveclass("harijaynoisyclass","moreeggs")
noisier_me.undecorated_function()
私は少し混乱しており、以下のコードが機能せず、構文エラーが発生する理由がわかりません。
これは正しく解釈されず、構文エラーが発生します。
class Myrepetitiveclass(Myclass):
def __init__(self,*args, **kwds):
Myclass.__init__(self,*args,**kwds)
# Why does this not work? and gives a syntax error?
@method_decorator(run_eight_times)
self.undecorated_function
再定義せずに子クラスの関数を装飾するにはどうすればよいですか?