如何在需要一个 arg 和 kwarg 的同时允许 args 和 kwargs; python
how to allow args and kwargs while requiring one arg and kwarg; python
我有一个函数:
def get_results(datasource, attribute='all_results', *args, **kwargs):
"""gets results for basic datasource format"""
print(args, kwargs)
ds = datasource(*args, **kwargs)
ds.get()
results = getattr(ds, attribute)
return results
叫得像
results = get_results(ThisDataSource, 'somestringID')
给予args/kwargs
(), {}
它的工作方式是
def get_results(datasource, *args, **kwargs):
"""gets results for basic datasource format"""
print(args, kwargs)
ds = datasource(*args, **kwargs)
ds.get()
results = ds.all_results()
return results
给予args/kwargs
('somestringID',), {}
这种旧方法不好,因为数据源可能需要 return 行、列等
它的工作方式为
results = get_results(ThisDataSource, 'somestringID')
导致
ds = ThisDataSource('somestringID')
我怎样才能在声明中给它一个默认值,但仍然允许 args 和 kwargs?
我想打电话给
results = get_results(ThisDataSource, 'somestringID', attribute='rows')
并具有 args = ('somestringID'), and retain access to
属性='rows'`
谢谢
假设第一个位置参数是 attribute.
def get_results(datasource, *args, **kwargs):
"""gets results for basic datasource format"""
attribute = 'all_results' # default value
if 'attribute' in kwargs:
# attribure was given explicitly in keyword params
attribute = kwargs['attribute']
else:
if len(args)>0:
# args contains at least 1 value - we suppose first value to be an attribute
# extract and remove it from args
attribute = args.pop(0)
print(attribute, args, kwargs)
...
我有一个函数:
def get_results(datasource, attribute='all_results', *args, **kwargs):
"""gets results for basic datasource format"""
print(args, kwargs)
ds = datasource(*args, **kwargs)
ds.get()
results = getattr(ds, attribute)
return results
叫得像
results = get_results(ThisDataSource, 'somestringID')
给予args/kwargs
(), {}
它的工作方式是
def get_results(datasource, *args, **kwargs):
"""gets results for basic datasource format"""
print(args, kwargs)
ds = datasource(*args, **kwargs)
ds.get()
results = ds.all_results()
return results
给予args/kwargs
('somestringID',), {}
这种旧方法不好,因为数据源可能需要 return 行、列等 它的工作方式为
results = get_results(ThisDataSource, 'somestringID')
导致
ds = ThisDataSource('somestringID')
我怎样才能在声明中给它一个默认值,但仍然允许 args 和 kwargs? 我想打电话给
results = get_results(ThisDataSource, 'somestringID', attribute='rows')
并具有 args = ('somestringID'), and retain access to
属性='rows'`
谢谢
假设第一个位置参数是 attribute.
def get_results(datasource, *args, **kwargs):
"""gets results for basic datasource format"""
attribute = 'all_results' # default value
if 'attribute' in kwargs:
# attribure was given explicitly in keyword params
attribute = kwargs['attribute']
else:
if len(args)>0:
# args contains at least 1 value - we suppose first value to be an attribute
# extract and remove it from args
attribute = args.pop(0)
print(attribute, args, kwargs)
...