Python Wrap Class Method

前端 未结 4 1669
逝去的感伤
逝去的感伤 2021-02-07 18:05

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 ty

4条回答
  •  猫巷女王i
    2021-02-07 18:39

    Use a Metaclass.

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

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

提交回复
热议问题