Extension methods in Python

Joan Venge picture Joan Venge · Feb 5, 2009 · Viewed 15.4k times · Source

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

MyRandomMethod()

on existing types like int?

myInt.MyRandomMethod()

Answer

Torsten Marek picture Torsten Marek · Feb 5, 2009

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.