在类中仅定义默认关键字参数一次
我有这样的类,其中每种方法都重复默认关键字参数值:
class Example:
def method_1(kwarg_a=None, kwarg_b=None):
# Do something with kwargs
pass
def method_2(kwarg_a=None, kwarg_b=None):
# Do something with kwargs
pass
def method_3(kwarg_a=None, kwarg_b=None):
# Do something with kwargs
pass
只需要一次定义关键字参数列表就很方便。我的意思是以下内容。
# Doesn't compile, just for illustration.
class Example:
kwargs = {'kwarg_a': None, 'kwarg_b': None}
def method_1(**kwargs):
# Do something with kwargs
pass
def method_2(**kwargs):
# Do something with kwargs
pass
def method_3(**kwargs):
# Do something with kwargs
pass
不幸的是,最后一个示例不起作用,因为kwargs
只有直接调用时才会扩展。它不会扩展默认值。
Python有这样的功能吗?如果没有,是否有类似的目标是必须仅定义默认关键字参数列表的目标?
I have a class like this, where the default keyword argument values are repeated for every method:
class Example:
def method_1(kwarg_a=None, kwarg_b=None):
# Do something with kwargs
pass
def method_2(kwarg_a=None, kwarg_b=None):
# Do something with kwargs
pass
def method_3(kwarg_a=None, kwarg_b=None):
# Do something with kwargs
pass
It would be convenient to only have to define the list of keyword arguments once. I mean something like the following.
# Doesn't compile, just for illustration.
class Example:
kwargs = {'kwarg_a': None, 'kwarg_b': None}
def method_1(**kwargs):
# Do something with kwargs
pass
def method_2(**kwargs):
# Do something with kwargs
pass
def method_3(**kwargs):
# Do something with kwargs
pass
Unfortunately, the last example doesn't work, as kwargs
would only be expanded if called directly. It doesn't expand default values.
Does Python have such a functionality? If not, is there something similar to achive the goal of having to define the list of default keyword arguments only once?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以做这样的事情,但我不建议这样做。当您写入时,请节省少量的打字,而代码在以后读取中不值得您引入的代码。
仅关键字参数的默认值分别存储在
__ kwdefaults __
中(这是将参数名称映射到值的映射,而不是简单的值元素)。请注意,您可以稍后修补默认参数值,但是您不能修补参数列表本身,因此在定义函数时仍必须指定参数列表。 (或者,如果可以的话,这将使您的代码更加不可读。)以上所有内容都可能针对Cpython,并且可能在其他实现中不起作用。
@Jonsharpe在评论中提到了一个装饰者。装饰员可以使用相同的方法:
You could do something like this, but I don't recommend it. Saving yourself a small amount of typing when you write the code is not worth the difficulty in later reading the code that you introduce.
Default values for keyword-only parameters are stored separately in
__kwdefaults__
(which is a mapping of parameter names to values, rather than a simple tuple of values).Note that you can patch the default argument values later, but you can't patch the parameter list itself, so you still have to specify the list of parameters when the function is defined. (Or if you can, it would make your code even more unreadable.) It's also possible that all of the above is specific to CPython, and may not work in other implementations.
@jonsharpe mentioned a decorator in a comment. A decorator could use the same approach: