首页 > 解决方案 > 传递字符串或值以用作回调以获取值

问题描述

我想调用这样的函数:

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

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

总而言之,我希望这段代码能够工作:

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'},])

标签: python

解决方案


以下任何方法(process1process2process3)都可以测试该字段是字符串还是函数。(如果字段都不是,例如整数,则结果会因方法而异。)

无论字段是方法还是普通函数,这些都将起作用。但是,如果您想将值传递给函数,那将更加复杂,您可能希望以不同的方式组织程序。

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()

推荐阅读