gpt4 book ai didi

python - python函数的编码风格

转载 作者:太空宇宙 更新时间:2023-11-04 06:48:54 27 4
gpt4 key购买 nike

需要意见。

我有一个定义一些数据的函数。我的想法是用户可以告诉它从文件中读取数据:

acquire_data('read_from_file',filename)

或者用户可以直接提供数据:

acquire_data('use_this_list',datalist)

所以这个函数会有类似这样的形式

def acquire_data(mode,arg2):
if mode == 'read_from_file':
inputs=open(arg2)
data = #etc.
else:
data = arg2 #or deepcopy(arg2) or whatever

好吧,这行得通,但似乎有点陈腐。特别是,“arg2”根据“mode”的值具有非常不同的功能。所以:这是好的代码吗?这是“pythonic”吗?有人看到更好的编码方法吗?谢谢。

最佳答案

def acquire_data(list_or_filename):
# assuming py3 here, for py2 use 'isinstance(list_or_filename, basestring)
if isinstance(list_or_filename, str):
with open(list_or_filename,"r") as f:
return acquire_data_from_file(f)
else:
return acquire_data_from_list(list_or_filename)

关于python - python函数的编码风格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15119883/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com