【发布时间】:2009-09-23 15:19:05
【问题描述】:
我想创建一个包装另一个类的类,这样当一个函数通过包装类运行时,也会运行一个 pre 和 post 函数。我希望包装类无需修改即可与任何类一起使用。
例如,如果我有这个课程。
class Simple(object):
def one(self):
print "one"
def two(self,two):
print "two" + two
def three(self):
print "three"
我可以这样使用它...
number = Simple()
number.one()
number.two("2")
到目前为止,我已经编写了这个包装类...
class Wrapper(object):
def __init__(self,wrapped_class):
self.wrapped_class = wrapped_class()
def __getattr__(self,attr):
return self.wrapped_class.__getattribute__(attr)
def pre():
print "pre"
def post():
print "post"
我可以这样称呼...
number = Wrapper(Simple)
number.one()
number.two("2")
除了改变第一行之外,可以和上面一样使用。
我想要发生的是,当通过包装类调用函数时,包装类中的 pre 函数被调用,然后被包装类中的所需函数然后是 post 函数。我希望能够在不更改包装类以及不更改函数调用方式的情况下做到这一点,只更改创建类实例的语法。例如 number = Simple() vs number = Wrapper(Simple)
【问题讨论】:
标签: python