好的,在 C# 中我们有类似的东西:
public static string Destroy(this string s) {
return "";
}
所以基本上,当你有一个字符串时,你可以这样做:
str = "This is my string to be destroyed";
newstr = str.Destroy()
# instead of
newstr = Destroy(str)
现在这很酷,因为在我看来它更具可读性。 Python有类似的东西吗?我的意思是不要这样写:
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
有什么建议吗?
最佳答案
您可以直接修改类,有时称为猴子补丁。
def MyMethod(self):
return self + self
MyClass.MyMethod = MyMethod
del(MyMethod)#clean up namespace
我不能 100% 确定您可以在 str 这样的特殊类上执行此操作,但对于您的用户定义的类来说没问题。
更新
您在评论中证实了我的怀疑,这对于像 str 这样的内置函数是不可能的。在这种情况下,我相信此类类没有类似于 C# 扩展方法。
最后,这些方法在 C# 和 Python 中的便利性带来了相关的风险。使用这些技术可以使代码更难理解和维护。
关于Python 扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7139111/