Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension methods in Python

Does Python have extension methods like C#? Is it possible to call a method like:

MyRandomMethod() 

on existing types like int?

myInt.MyRandomMethod() 
like image 699
Joan Venge Avatar asked Feb 05 '09 00:02

Joan Venge


People also ask

What is extension method in Python?

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.

What is extension method with example?

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.

What is extension method in OOP?

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.


1 Answers

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.

like image 99
Torsten Marek Avatar answered Sep 21 '22 23:09

Torsten Marek