下列方法之一(
   
    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()