问题描述
如果我有对象
>>> class example_class(): >>> def example_function(number, text = 'I print this: '): >>> print text, number
我可以更改example_function输入参数
I can change the example_function input parameter
>>> example_instance = example_class() >>> print example_instace.example_function(3, text = 'I print that: ')
每次使用 example_instace 时,总是使用我打印:。是否可以更改 text 的默认值,以便我得到此行为:
Now I would like to always use I print that: every time I use example_instace. Is it possible to change the default value of text so that I get this behavior:
>>> example_instace = example_class() >>> print example_instance.example_function(3) I print this: 3 >>> default_value(example_instance.text, 'I print that: ') >>> print example_instance.example_function(3) I print that: 3
推荐答案
函数默认值与函数一起存储,函数对象用于创建方法包装器。您不能在每个实例的基础上更改默认值。
Function defaults are stored with the function, and the function object is used to create the method wrapper. You cannot alter that default on a per-instance basis.
相反,使用sentinel来检测默认值已被选中; 无是适用于无本身不是有效值的常见哨兵:
Instead, use a sentinel to detect that the default has been picked; None is a common sentinel suitable for when None itself isn't a valid value:
class example_class(): _example_text_default = 'I print this: ' def example_function(self, number, text=None): if text is None: text = self._example_text_default print text, number
,然后只需在每个实例的基础上设置 self._example_text_default 即可覆盖。
and then simply set self._example_text_default on a per-instance basis to override.
None 不是合适的标记,请为作业创建唯一的单例对象:
If None is not a suitable sentinel, create a unique singleton object for the job:
_sentinel = object() class example_class(): _example_text_default = 'I print this: ' def example_function(self, number, text=_sentinel): if text is _sentinel: text = self._example_text_default print text, number
$ b b
,现在您可以使用 example_class()。example_function(42,无)作为有效的非默认值。
and now you can use example_class().example_function(42, None) as a valid non-default value.
这篇关于如何更改对象的实例的函数参数的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!