【问题标题】:Python - Passing a function with multiple arguments into another functionPython - Passing a function with multiple arguments into another function
【发布时间】:2022-12-02 05:04:08
【问题描述】:

I have this method that I want to passintoanother function.

def get_service_enums(context, enum):
   svc = Service(context)
   return svc.get_enum(enum)

I want to pass this function is as a parameter to another class.

ColumnDef(enum_values=my_func)

Ideally, my_func is get_service_enums. However get_service_enums has a second parameter, enum that I want to pass in at same time I pass in get_service_enums. How can I do this without actually invoking get_service_enums with parenthesis?

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    using partial from functools.

    from functools import partial
    
    def get_service_enums(context, enum):
        print(context, enum)
    
    partial_function = partial(get_service_enums, enum="second_thing")
    partial_function("first_thing")
    
    first_thing second_thing
    

    【讨论】:

      【解决方案2】:

      Does it not work for you to pass the function and its argument separately

      ColumnDef(enum_values=get_service_enums, enum)
      

      with the class ColumnDef in charge of passing in enum when the function is invoked?

      If not, functools.partial is your friend:

      import functools
      
      # New version of get_service_enums with enum = 42
      my_func = functools.partial(get_service_enums, enum=42)
      my_func('hello')  # hello, 42
      
      ColumnDef(enum_values=my_func)
      

      【讨论】:

        猜你喜欢
        • 2022-12-01
        • 2022-12-01
        • 1970-01-01
        • 2015-08-10
        • 1970-01-01
        • 2020-04-07
        • 2022-12-02
        • 2022-12-02
        • 1970-01-01
        相关资源
        最近更新 更多