python - 传递字符串或值以用作回调以获取值
问题描述
我想调用这样的函数:
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'},])
解决方案
以下任何方法(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()
推荐阅读
- django - ImportError:没有名为 social_django.middleware 的模块
- javascript - 如何清除浏览缓存 - index.html 卡在缓存中
- php - 如何从我的网站中的某些特定页面隐藏包含在标题页面中?
- python - Selenium、Python、Marionette 证书警告
- reactjs - className 属性不会采用 CSSProperties 类型 - React、Material-UI、TypeScript 4.1
- r - 为什么`difftime`带有R中其他变量的标签属性?
- python - Python:在元组列表中找到包含特定字符串的单词
- java - 您好,每次我调用存在于名为“Firstfragment”的片段中的 Spinner 时,我的应用程序都会崩溃
- netlogo - 有没有办法将文本字符串作为命令执行?
- html - 网页结构在缩放时未保持对齐