我有小问题。当我使用require 'rails_helper'
RSpec.describe ScheduleTimeSlotsController, type: :controller do
describe 'GET #get_available_schedules when for_date is today' do
it 'returns http success' do
for_date = Date.today
available_schedules = ScheduleTimeSlot.where(
doctor_id: params[:dr_id],
date: params[:for_date].to_date,
status: 'vacant',
archive: false
).where(
'start_time >=?',
Time.now.seconds_since_midnight
).reorder(:start_time)
get 'get_available_schedules', for_date: for_date
expect(response.body.available_schedules).to eq(available_schedules)
end
end
describe 'GET #get_available_schedules when for_date is not today' do
it 'returns http success' do
for_date = Date.yesterday
available_schedules = ScheduleTimeSlot.where(
doctor_id: params[:dr_id], date: params[:for_date].to_date,
status: 'vacant',
archive: false
).reorder(:start_time)
get 'get_available_schedules', for_date: for_date
expect(response.body.available_schedules).to eq(available_schedules)
end
end
end
创建一个新函数时,我希望根据某个变量在函数末尾更改def
。例如:
i
有可能做点什么吗? 谢谢
答案 0 :(得分:2)
我很确定其他人在这里错过了明显的解决方案。
def happy(i):
names = ['Paul', 'Peter']
...
print('Happy birthday to {}'.format(names(i)))
答案 1 :(得分:0)
您可以使用:
locals()["Happy_" + i]()
或
globals()["Happy_" + i]()
locals()["Happy_" + i]
将从本地人处获取该功能,最终()
将调用该功能。
答案 2 :(得分:0)
import time
i = 2
def Happy_1():
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday dear Paul")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("END")
def Happy_2():
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday dear Peter")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("END")
def error():
print('No such function!')
print locals().get('Happy_{}'.format(i), error)()
答案 3 :(得分:0)
感谢@ Daniel Roseman指出这一点。
Python的禅宗 - 简单比复杂更好。
请检查此代码。
import time
i = 2
def Happy(i):
if i == 1:
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday dear Paul")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("END")
elif i == 2:
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("Happy Brithday dear Peter")
time.sleep(1)
print("Happy Brithday to you")
time.sleep(1)
print("END")
Happy(i)
输出:
C:\Users\dinesh_pundkar\Desktop>python demo.Py
Happy Brithday to you
Happy Brithday to you
Happy Brithday dear Peter
Happy Brithday to you
END