[英]What's a more pythonic way to write this function declaration
This is parred down to the most basic elements for the sake of brevity. 为了简洁起见,将其简化为最基本的元素。 I understand that the below is redundant as written, but I digress. 我了解以下内容在书面上是多余的,但我离题了。
I want to know if there's a smarter, more concise way to write this 我想知道是否有一种更聪明,更简洁的方式编写此代码
def create_action(context, verb, actor = None, target = None, permission_level = None):
action = Action(context = context, verb = verb, actor = actor, target = target, permission_level = permission_level)
As you can see, two required arguments, a handful (or potentially more) optional ones overloaded. 如您所见,两个必需的参数(少数(或可能更多)可选参数)已重载。
What's a better way to write this so that I am not slinging around these keywords? 有什么更好的写方法,这样我就不会在这些关键字周围乱花呢?
Use unpacking of arguments : 使用参数解压缩 :
def create_action(*args, **kwargs):
action = Action(*args, **kwargs)
First off, remove spaces between the parts of default args. 首先,删除默认args部分之间的空格。 You also probably don't need to use keyword arguments for the call to Action()
eg 您可能也不需要在调用Action()
使用关键字参数,例如
def create_action(context, verb, actor=None, target=None, permission_level=None):
action = Action(context, verb, actor, target, permission_level)
That's the conventional Python style for using default arguments. 这是使用默认参数的常规Python样式。
Frankly, I don't see why this function is necessary at all. 坦白说,我根本不明白为什么需要此功能。 it doesn't return anything (I guess you just forgot to return action, and everything it accomplishes ought to be done in the __init__
method for the Action
class (I assume it's a class), eg 它不会返回任何内容(我想您只是忘记了返回操作,而它所完成的一切都应该在Action
类的__init__
方法中完成(我假设它是一个类),例如
class Action(object):
def __init__(context, verb, actor=None, target=None, permission_level=None):
# Do something
For brevity, I wouldn't write the function at all and just use default arguments in the __init__
method of the class. 为简便起见,我根本不会编写函数,而只在类的__init__
方法中使用默认参数。
If you want to: 如果你想:
context
and verb
are explicitly passed 确保明确传递context
和verb
You can do something like this. 你可以做这样的事情。
optional = ('actor', 'target', 'permission_level')
def create_action(context, verb, **opt):
args = dict([(k, opt.get(k, None) for k in optional])
action = Action(context, verb, **args)
or this if you want to pass them all as named arguments. 或者如果您要将它们全部作为命名参数传递,则此操作。
optional = (('actor', None), ('target', None), ('permission_level', None))
required = ('context', 'verb')
def create_action(*a, **kv):
req = zip(required, a)
opt = [(t[0], kv.get(t[0], t[1])) for t in optional]
action = Action(**dict(req + opt))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.