我在Python中遇到问题,为此我找不到任何干净的解决方案...
在调用某些方法时,我想在方法执行之前和之后执行一些代码。为了(除其他外)自动设置和清理context变量。
为了实现这一点,我已经宣布了以下元类:
class MyType(type):
def __new__(cls, name, bases, attrs):
#wraps the 'test' method to automate context management and other stuff
attrs['test'] = cls.other_wrapper(attrs['test'])
attrs['test'] = cls.context_wrapper(attrs['test'])
return super(MyType, cls).__new__(cls, name, bases, attrs)
@classmethod
def context_wrapper(cls, operation):
def _manage_context(self, *args, **kwargs):
#Sets the context to 'blabla' before the execution
self.context = 'blabla'
returned = operation(self, *args, **kwargs)
#Cleans the context after execution
self.context = None
return returned
return _manage_context
@classmethod
def other_wrapper(cls, operation):
def _wrapped(self, *args, **kwargs):
#DO something with self and *args and **kwargs
return operation(self, *args, **kwargs)
return _wrapped这就像一种魅力:
class Parent(object):
__metaclass__ = MyType
def test(self):
#Here the context is set:
print self.context #prints blabla但只要我想要继承Parent,就会出现问题,当我使用super调用父方法时:
class Child(Parent):
def test(self):
#Here the context is set too
print self.context #prints blabla
super(Child, self).test()
#But now the context is unset, because Parent.test is also wrapped by _manage_context
#so this prints 'None', which is not what was expected
print self.context我曾想过在将它设置为新值之前保存上下文,但这只能部分解决问题......
确实,(这一点很难解释),父方法被调用,包装器被执行,但是他们接收到*args和**kwargs,发给Parent.test,而self是Child实例,所以如果我想要self属性有不相关的值用*args和**kwargs来挑战他们(例如,用于自动验证目的),例如:
@classmethod
def validation_wrapper(cls, operation):
def _wrapped(self, *args, **kwargs):
#Validate the value of a kwarg
#But if this is executed because we called super(Child, self).test(...
#`self.some_minimum` will be `Child.some_minimum`, which is irrelevant
#considering that we called `Parent.test`
if not kwarg['some_arg'] > self.some_minimum:
raise ValueError('Validation failed')
return operation(self, *args, **kwargs)
return _wrapped所以基本上,要解决这个问题,我看到两个解决方案:
防止在使用super(Child, self)调用方法时执行包装
拥有始终为“正确”类型的self
这两种解决方案对我来说似乎都不可能...有人对如何解决这个问题有想法吗?一条建议 ?