Python Wrap Class Method

前端 未结 4 1724
逝去的感伤
逝去的感伤 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条回答
  •  轮回少年
    2021-02-07 18:54

    What other folks do

    class A:
       def do_run( self ):
           """Must be overridden."""
           raise NotImplementedError
       def run( self, *args, **kw ):
           """Must not be overridden.
           You were warned.
           """
           print "PRE"
           return_value = self.do_run(*args, **kw)
           print "POST"
           return return_value
    
    class B(A):
        def do_run(self):
            print "Run B"
            return True
    

    That's usually sufficient.

    If you want to worry about someone "breaking" this, stop now. Don't waste time worrying.

    It's Python. We're all adults here. All the malicious sociopaths will break all you code by copying it, changing it, and then breaking it. No matter what you do, they'll just copy your code and modify it to break the clever bits.

    Everyone else will read your comment and stick by your rules. If they want to use your module/package/framework, they will cooperate.

提交回复
热议问题