Skip to main content
 首页 » 编程设计

python之python函数的编码风格

2025年05月04日13Leo_wl

需要意见。

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

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)