我正在嘗試編寫修改其類的狀態的類方法裝飾器。目前我遇到了麻煩。修改綁定方法及其類的Python裝飾器狀態
側面問題:什麼時候裝飾器被調用?它是在類被實例化的時候加載的,還是在類讀取的讀取期間加載的?
我想要做的是這樣的:
class ObjMeta(object):
methods = []
# This should be a decorator that magically updates the 'methods'
# attribute (or list) of this class that's being read by the proxying
# class below.
def method_wrapper(method):
@functools.wraps(method)
def wrapper(*args, **kwargs):
ObjMeta.methods.append(method.__name__)
return method(*args, **kwargs)
return wrapper
# Our methods
@method_wrapper
def method1(self, *args):
return args
@method_wrapper
def method2(self, *args):
return args
class Obj(object):
klass = None
def __init__(self, object_class=ObjMeta):
self.klass = object_class
self._set_methods(object_class)
# We dynamically load the method proxies that calls to our meta class
# that actually contains the methods. It's actually dependent to the
# meta class' methods attribute that contains a list of names of its
# existing methods. This is where I wanted it to be done automagically with
# the help of decorators
def _set_methods(self, object_class):
for method_name in object_class:
setattr(self, method_name, self._proxy_method(method_name))
# Proxies the method that's being called to our meta class
def _proxy_method(self, method_name):
def wrapper(*fargs, **fkwargs):
return getattr(self.klass(*fargs, **fkwargs), method_name)
return wrapper()
我認爲這是醜陋的類手工編寫的方法列表,這樣也許會裝飾解決這個問題。
這是一個開源項目,我正在將端口underscore.js工作到python。我明白,它說我應該只使用itertools什麼的。我只是爲了愛編程和學習而做這個。順便說一句,項目託管here
謝謝!
裝飾者應該在創建類對象時運行。 (*不是*當這個類的實例正在創建時。)這通常發生在第一次導入模塊時。 – millimoose
謝謝!這回答了我的另一個問題。幫助很多。 – jpanganiban
這與函數式編程有什麼關係? – Ben