Python Wrap类方法

Joe*_*e J 11 python methods class wrapper

我正在尝试使用一个将由_wrap_run方法包装的run方法创建一个对象.我希望能够通过简单地键入instance.run()来调用方法和它的包装器,并且我希望能够对该对象进行子类化,以便我可以覆盖run()方法并让它仍然执行包装器.

更简单地说,我希望人们能够子类化A并覆盖run()但仍然调用run()方法执行包装函数.

我对这个机制有些困难.有没有人对这种方法有任何建议?谢谢阅读.

class A:

    def run(self):
        print "Run A"
        return True

    def _wrap_run(self):
        print "PRE"
        return_value = self.run()
        print "POST"
        return return_value

    run = property(_wrap_run)


a = A()
a.run()
"""
Should Print: 
PRE
Run A
POST
"""


class B(A):

    def run(self):
        print "Run B"
        return True

b = B()
b.run()
"""
Should Print: 
PRE
Run B
POST
"""
Run Code Online (Sandbox Code Playgroud)

agf*_*agf 14

使用元类.

class MetaClass(type):
    @staticmethod
    def wrap(run):
        """Return a wrapped instance method"""
        def outer(self):
            print "PRE",
            return_value = run(self)
            print "POST"
            return return_value
        return outer
    def __new__(cls, name, bases, attrs):
        """If the class has a 'run' method, wrap it"""
        if 'run' in attrs:
            attrs['run'] = cls.wrap(attrs['run'])
        return super(MetaClass, cls).__new__(cls, name, bases, attrs)

class MyClass(object):
    """Use MetaClass to make this class"""
    __metaclass__ = MetaClass
    def run(self): print 'RUN',

myinstance = MyClass()

# Prints PRE RUN POST
myinstance.run()
Run Code Online (Sandbox Code Playgroud)

现在,如果其他人继承MyClass,他们仍然会run()包装他们的方法.


Cat*_*lus 5

最简单的方法:使run包装器和私有方法成为可重写的方法。

class A(object):
    def run(self):
        print "PRE"
        return_value = self._inner_run()
        print "POST"
        return return_value

    def _inner_run(self):
        print "Run A"
        return True

class B(A):
    def _inner_run(self):
        print "Run B"
        return True
Run Code Online (Sandbox Code Playgroud)