Search code examples
pythonextension-methods

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?


Solution

  • After a week, I have a solution that is closest to what I was seeking for. The solution consists of using getattr and __getattr__. Here is an example for those who are interested.

    class myClass:
    
        def __init__(self): pass
    
        def __getattr__(self, attr): 
            try:
                methodToCall = getattr(myClass, attr)
                return methodToCall(myClass(), self)
            except:
                pass
    
        def firstChild(self, node):
            # bla bla bla
        def lastChild(self, node):
            # bla bla bla 
    
    x = myClass()
    div = x.getMYDiv()
    y = div.firstChild.lastChild 
    

    I haven't test this example, I just gave it to give an idea for who might be interested. Hope that helps.