Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python extension methods

OK, in C# we have something like:

public static string Destroy(this string s) {      return ""; } 

So basically, when you have a string you can do:

str = "This is my string to be destroyed"; newstr = str.Destroy() # instead of  newstr = Destroy(str) 

Now this is cool because in my opinion it's more readable. Does Python have something similar? I mean instead of writing like this:

x = SomeClass() div = x.getMyDiv() span = x.FirstChild(x.FirstChild(div)) # so instead of this 

I'd like to write:

span = div.FirstChild().FirstChild() # which is more readable to me 

Any suggestion?

like image 802
Shaokan Avatar asked Aug 21 '11 15:08

Shaokan


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 are extension methods used for?

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 just modify the class directly, sometimes known as monkey patching.

def MyMethod(self):       return self + self  MyClass.MyMethod = MyMethod del(MyMethod)#clean up namespace 

I'm not 100% sure you can do this on a special class like str, but it's fine for your user-defined classes.

Update

You confirm in a comment my suspicion that this is not possible for a builtin like str. In which case I believe there is no analogue to C# extension methods for such classes.

Finally, the convenience of these methods, in both C# and Python, comes with an associated risk. Using these techniques can make code more complex to understand and maintain.

like image 186
David Heffernan Avatar answered Sep 18 '22 22:09

David Heffernan