How to define enum values that are functions?

后端 未结 2 1621
名媛妹妹
名媛妹妹 2021-01-04 03:32

I have a situation where I need to enforce and give the user the option of one of a number of select functions, to be passed in as an argument to another function:

I

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-04 04:07

    In addition to the answer of Bakuriu... If you use the wrapper approach like above you loose information about the original function like __name__, __repr__ and so on after wrapping it. This will cause problems for example if you want to use sphinx for generation of source code documentation. Therefore add the following to your wrapper class.

    class wrapper:
        def __init__(self, function):
            self.function = function
            functools.update_wrapper(self, function)
        def __call__(self,*args, **kwargs):
            return self.function(*args, **kwargs)
        def __repr__(self):
            return self.function.__repr__()
    

提交回复
热议问题