我刚开始学习python
我创建了此函数,但是正如您在“ if”语句中看到的那样,我已经复制了代码
我只将file_id = filename.photo[-1].file_id
更改为file_id = filename.video.file_id
使该功能正常工作,但是如何缩短这段代码
谢谢您的时间
def create_post(filename):
if filename.content_type == 'photo':
file_id = filename.photo[-1].file_id
file = bot.get_file(file_id)
downloaded_file = bot.download_file(file.file_path)
with open("image.jpg", 'wb') as new_file:
new_file.write(downloaded_file)
image = 'image.jpg'
token = store_file_temporary(image)
headers = {
"content-type": "multipart/form-data",
"Accept": "application/json",
"Content-Type": "application/json"
}
filesd = {
"title": randomString(),
"safety": 'safe',
"contentToken": token
}
r = requests.post(url=url + "/posts/", json=filesd, auth=(username, password),
headers=headers)
print(r.json())
return r.json()
elif filename.content_type == 'video':
file_id = filename.video.file_id
file = bot.get_file(file_id)
downloaded_file = bot.download_file(file.file_path)
with open("image.jpg", 'wb') as new_file:
new_file.write(downloaded_file)
image = 'image.jpg'
token = store_file_temporary(image)
headers = {
"content-type": "multipart/form-data",
"Accept": "application/json",
"Content-Type": "application/json"
}
filesd = {
"title": randomString(),
"safety": 'safe',
"contentToken": token
}
r = requests.post(url=url + "/posts/", json=filesd, auth=(username, password),
headers=headers)
print(r.json())
return r.json()
答案 0 :(得分:2)
一旦获得file_id = filename.photo[-1].file_id
,从那里开始基本上就是完全相同的处理。因此,只需将此行放入if else
中,其余的就放置一个方法。
if filename.content_type == 'photo':
file_id = filename.photo[-1].file_id
elif filename.content_type == 'video':
file_id = filename.video.file_id
//call some method with file_id where you do the rest of the work.
somemeaningful_function_name(file_id)
def somemeaningful_function_name(file_id):
//work with file_id
您自己说过DRY原理。当接近这样的事情时,只是去寻找重复部分。根据经验,如果多次重复使用相同的代码块,只需将其放入函数中并使用即可。