Does Python have extension methods like C#? Is it possible to call a method like:
MyRandomMethod()
on existing types like int
?
myInt.MyRandomMethod()
The Python's List extend() method iterates over an iterable like string, list, tuple, etc., and adds each element of the iterable to the end of the List, modifying the original list.
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.
In object-oriented computer programming, an extension method is a method added to an object after the original object was compiled. The modified object is often a class, a prototype or a type. Extension methods are features of some object-oriented programming languages.
You can add whatever methods you like on class objects defined in Python code (AKA monkey patching):
>>> class A(object): >>> pass >>> def stuff(self): >>> print self >>> A.test = stuff >>> A().test()
This does not work on builtin types, because their __dict__
is not writable (it's a dictproxy
).
So no, there is no "real" extension method mechanism in Python.
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