Python extension methods

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

    You can achieve this nicely with the following context manager that adds the method to the class or object inside the context block and removes it afterwards:

    class extension_method:
    
        def __init__(self, obj, method):
            method_name = method.__name__
            setattr(obj, method_name, method)
            self.obj = obj
            self.method_name = method_name
    
        def __enter__(self):
            return self.obj
    
        def __exit__(self, type, value, traceback):
            # remove this if you want to keep the extension method after context exit
            delattr(self.obj, self.method_name)
    
    

    Usage is as follows:

    class C:
        pass
    
    def get_class_name(self):
        return self.__class__.__name__
    
    with extension_method(C, get_class_name):
        assert hasattr(C, 'get_class_name') # the method is added to C
        c = C()
        print(c.get_class_name()) # prints 'C'
    
    assert not hasattr(C, 'get_class_name') # the method is gone from C
    

提交回复
热议问题