代码之家  ›  专栏  ›  技术社区  ›  Olivier Pons

传递字符串或值以用作回调以获取值

  •  0
  • Olivier Pons  · 技术社区  · 7 年前

    我想调用这样的函数:

    c = selion([{'title': "mytitle1",
                 'my_field': 'value_1',
                 'other': 'other_value'},
                {'title': "mytitle2",
                 'my_field': 'value_2',
                 'other': 'other_value'},])
    

    问题是我想 'my_field' 有时是一个回调函数。

    • 如何测试,在 selion() 函数,如果它是字符串或函数并调用它?
    • 如果我想传入一个类内的函数(比如 self.calculate('client_x') ),它是否像正常功能一样在开箱即用?

    总而言之,我希望这段代码起作用:

    class Test():
        def calculate_value(self):
            return 'test'
    
        c = self.selion([{'title': "mytitle1",
                          'my_field': self.calculate_value,
                          'other': 'other_value'},
                         {'title': "mytitle2",
                          'my_field': 'value_2',
                          'other': 'other_value'},])
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Stuart    7 年前

    下列方法之一( process1 ,请 process2 process3 )测试字段是字符串还是函数。(如果两个字段都不是,则结果会因方法而异,例如整数。)

    不管字段是方法还是普通函数,这些都可以工作。但是,如果要将值传递给函数,则会更复杂,并且可能需要以不同的方式组织程序。

    class Test():
        def calculate_value(self):
            return 'test'
    
        def process1(self, x):
            """ Return x if it's a string or if not call it as a function """
            if isinstance(x, str):
                return x
            else:
                return x()
    
        def process2(self, x):
            """ Try to call x as a function and return the result, and if it doesn't work just return x """
            try:
                return x()
            except TypeError:
                return x
    
        def process3(self, x):
            """ Call x and return the result if it's callable, or if not just return x """
            if callable(x):
                return x()
            else:
                return x    
    
        def selion(self, data):
            # You can use self.process1, self.process2, or self.process3 here with
            # similar results
            return [self.process1(x['my_field']) for x in data]
    
        def do_stuff(self):
            c = self.selion([
                {
                    'title': "mytitle1",
                    'my_field': self.calculate_value,
                    'other': 'other_value'
                },
                {
                    'title': "mytitle2",
                    'my_field': 'value_2',
                    'other': 'other_value'
                },
            ])
            print(c)
    
    
    test = Test()
    test.do_stuff()