Python extension methods

后端 未结 7 1934
星月不相逢
星月不相逢 2021-02-02 06:39

OK, in C# we have something like:

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

So basically, when you have a string you ca

7条回答
  •  一整个雨季
    2021-02-02 07:29

    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.

提交回复
热议问题