I've installed a third party library tornado by pip and need to override a method, say to_unicode
defined in the global scope of a module say tornado.escape
. So that all calls to that method will use my overridden version. Or maybe, I would want to control it so that only my code will use the overridden version.
If it had been defined inside a class, I'd have no problem to subclass it and override the method! But since this is just a method, I'm wondering how to override it.
Surprisingly, I found not suitable solution in SO, is this kind of impossible to achieve?
In Python method overriding occurs by simply defining in the child class a method with the same name of a method in the parent class. When you define a method in the object you make this latter able to satisfy that method call, so the implementations of its ancestors do not come in play.
You can do it still, by naming your object just so: def _Foo__method(self): where you prefix the method name with one more underscore and the defining classname (so in this case prefixed with _Foo ). The process of renaming methods and attributes with a double underscore is called private name mangling.
Python has a number of built-in functions that are always accessible in the interpreter. Unless you have a special reason, you should neither overwrite these functions nor assign a value to a variable that has the same name as a built-in function.
The __module__ property is intended for retrieving the module where the function was defined, either to read the source code or sometimes to re-import it in a script.
You can simply rebind the name of an object (in this case, a module-level function) to a different object. For example, if you want to have math.cos
work with degrees instead of radians, you could do
>>> import math
>>> math.cos(90)
-0.4480736161291701
>>> old_cos = math.cos
>>> def new_cos(degrees):
... return old_cos(math.radians(degrees))
...
>>> math.cos = new_cos
>>> math.cos(90)
6.123233995736766e-17
However, that might cause problems to other functions that use that module...
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