Python扩展方法

编程入门 行业动态 更新时间:2024-10-26 14:36:10
本文介绍了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扩展方法

本文发布于:2023-11-05 18:58:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1561599.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!