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.
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
"""
What are Wrappers in Python? So, wrappers are the functionality available in Python to wrap a function with another function to extend its behavior. Now, the reason to use wrappers in our code lies in the fact that we can modify a wrapped function without actually changing it. They are also known as decorators.
In Python, wrappers are modifications to functions or classes which change the behavior in some way. They are called wrappers because they “wrap” around the existing code to modify it. This is most commonly used with function wrapping, but we can also wrap classes.
Program Explanation:First, we create one function which is named as a wrapper Example. Next, create class Wrapper and two functions i.e __init__ and get_name. The function __init__ is used to initialize the function. Here A(y) returns an object to class code.
Decoration is a way to specify management code for functions and classes. Decorators themselves take the form of callable objects that process other callable objects.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With