如何在默认为类级别值的 Python 方法中使用命名参数?
使用场景:
# case #1 - for classes
a = MyClass() # default logger is None
a = MyClass(logger="a") # set the default logger to be "a"
a.test(logger="b") # this means that logger will be "b" only inside this method
a.test(logger=None) # this means that logger will be None but only inside this method
a.test() # here logger should defaults to the value specified when object was initialized ("a")
如何实现MyClass
以便能够像上面那样使用它?
假设我在 MyClass
中有几个可以接受 logger
命名参数的方法,因此我希望有一个不需要在开始时添加大量重复代码的解决方案每个 test...()
方法。
我读到了哨兵示例,但这确实不适用于类,我不想添加全局变量来将哨兵对象保留在内部。
Usage scenario:
# case #1 - for classes
a = MyClass() # default logger is None
a = MyClass(logger="a") # set the default logger to be "a"
a.test(logger="b") # this means that logger will be "b" only inside this method
a.test(logger=None) # this means that logger will be None but only inside this method
a.test() # here logger should defaults to the value specified when object was initialized ("a")
How can I implement MyClass
in order to be able to use it as above?
Let's assume that I have several methods inside MyClass
that can accept the logger
named parameter so I would appreciate a solution that does not require to add a lot of duplicate code at the beginning of each test...()
method.
I read about the sentinel example, but this does not work for classes and I would not like to add a global variable to keep the sentinel object inside.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
两个核心思想:捕获可能(或可能不)本地覆盖到关键字参数字典中的一组命名值;使用哨兵对象作为默认值来唯一标识某个命名参数是否已显式传递(
None
通常用于此目的,但是当您想要None 时,就像这里一样)
作为参数的“一流值”,唯一的哨兵对象也可以。two core ideas: capturing the set of named values that may be (or may not be) locally overridden into a keywords-parameters dict; using a sentinel object as the default value to uniquely identify whether a certain named argument has been explicitly passed or not (
None
is often used for this purpose, but when, as here, you wantNone
as a "first class value" for the parameter, a unique sentinel object will do just as well).注意
**kwargs
是必要的,因为您允许在MyClass.test
中为名为变量的记录器使用None
值。如果您选择了其他一些标记值,则可以取消此设置(但最常见的是None
)。MyClass
实例的默认记录器是None
,在MyClass
构造函数中设置。Notes
**kwargs
is necessary as you're allowingNone
values for the logger named variable inMyClass.test
. You could do away with this if you picked some other sentinel value (butNone
is most common).MyClass
instances isNone
, set in theMyClass
constructor.简要说明:
test
首先假设它将使用实例记录器。但是,如果显式记录器作为命令行参数传入,它将被使用。如果 logger = None 作为关键字参数传递,则不使用记录器。Brief explanation:
test
starts off by assuming that it is going to use the instance logger. However if an explicit logger is passed in as command line argument it will be used instead. Iflogger = None
is passed as a key word argument then no logger is used.