我在这里找到了资源,但它们与本地嵌入式功能有关。我有一个名为“test”的文件,另一个名为“main”。我希望测试包含我的所有逻辑,而main将包含一个完整的功能列表,每个功能都与健康保险政策相关。有数百个策略,因此每次在每个“test”中编写一个if语句会变得非常繁琐。我想写尽可能少的行来根据值所声明的函数来调用函数。类似的东西:
insurance = input()
最终结果不是输入,而是用于测试/学习目的。如果存在,输入将始终与保险单完全相关。所以在“测试”中,我目前有:
from inspolicy.main import bcbs, uhc, medicare
print('What is the insurance?(bcbs, uhc, medicare)')
insurance = input()
if insurance.lower() == 'bcbs':
bcbs()
elif insurance.lower() == 'uhc':
uhc()
elif insurance.lower() == 'medicare':
medicare()
else:
print('This policy can not be found in the database. Please set aside.')
“main”包括:
def bcbs():
print('This is BCBS')
def uhc():
print('This is UHC')
def medicare():
print('This is Medicare')
那么有没有办法让输入(即保险)被引用来从“main”调用函数?
提前感谢您的时间!
答案 0 :(得分:1)
最好的方法是使用字典在保险单的名称和处理它们的功能之间进行映射。这可能是你的一个模块中的手工构建的dict,或者你可以简单地使用main
模块的命名空间(使用字典实现):
# in test
import types
import inspolicy.main # import the module itself, rather than just the functions
insurance = input('What is the insurance?(bcbs, uhc, medicare)')
func = getattr(inspolicy.main, insurance, None)
if isinstance(func, types.FunctionType):
func()
else:
print('This policy can not be found in the database. Please set aside.')
答案 1 :(得分:0)
我们认为这是您的class YourModel < ActiveRecord
validates_presence_of :per_day
...
end
main.py
可以在def uhc():
print("This is UHC")
中执行类似的操作:
test.py
然后,如果输入“uhc”作为输入,您将从main.py获取uhc函数并调用它。