1 回答

TA貢獻1818條經(jīng)驗 獲得超8個贊
我同意@Dennis:if 語句使代碼非常易讀。以下是我在不使用if. 也許有更好的方法,例如使用format語句而不是“f-strings”,并且正如@Dennis 建議的那樣,也許使用類型作為鍵。
def upload_location(instance, filename):
lookup = dict([
(Story.__name__, lambda instance: f'stories/{instance.id}/cover{extension}'),
(Episode.__name__, lambda instance: f'stories/{instance.story.id}/{instance.index}/cover{extension}'),
(EpisodeSlide.__name__, lambda instance: f'stories/{instance.episode.story.id}/{instance.episode.index}/{instance.id}{extension}')
])
_, extension = os.path.splitext(filename)
loc = lookup[instance.__class__.__name__](instance)
return loc
print(upload_location(e, "hello.txt"))
print(upload_location(es, "hello.txt"))
print(upload_location(s, "hello.txt"))
stories/1/10/cover.txt
stories/1/10/100.txt
stories/1/cover.txt
再說一遍,if 語句比上面的函數(shù)要好得多!!
添加回答
舉報