Python extension methods

后端 未结 7 1930
星月不相逢
星月不相逢 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:31

    You can just modify the class directly, sometimes known as monkey patching.

    def MyMethod(self):
          return self + self
    
    MyClass.MyMethod = MyMethod
    del(MyMethod)#clean up namespace
    

    I'm not 100% sure you can do this on a special class like str, but it's fine for your user-defined classes.

    Update

    You confirm in a comment my suspicion that this is not possible for a builtin like str. In which case I believe there is no analogue to C# extension methods for such classes.

    Finally, the convenience of these methods, in both C# and Python, comes with an associated risk. Using these techniques can make code more complex to understand and maintain.

提交回复
热议问题