Python包装类方法 [英] Python Wrap Class Method

查看:209
本文介绍了Python包装类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create an object with a run method that will be wrapped by a _wrap_run method. I'd like to be able to call the method and it's wrapper by simply typing instance.run() and I'd like to be able to subclass the object so I can override the run() method and have it still execute the wrapper.

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

More simply put, I want people to be able to subclass A and override run() but still have calls to the run() method execute the wrapper function.

我在机制上遇到了一些困难.有人对这种方法有什么建议吗?

I'm having some difficulty with the mechanics of this. Does anyone have any suggestions regarding this approach?

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
"""

推荐答案

使用元类.

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()

现在,如果其他人继承了MyClass的子类,他们仍然会使用他们的run()方法.

Now if other people subclass MyClass, they will still get their run() methods wrapped.

这篇关于Python包装类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆