Python扩展方法 [英] Python extension methods

查看:95
本文介绍了Python扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,在C#中我们有类似的东西:

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)

现在这很酷,因为在我看来,它更具可读性. Python有类似的东西吗?我的意思是不要这样写:

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

我想写:

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

有什么建议吗?

推荐答案

一个星期后,我有一个最接近所要解决方案的解决方案.解决方案包括使用getattr__getattr__.这是有兴趣的人的例子.

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.

这篇关于Python扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆