好的,在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扩展方法
发布评论