Python 如何更改对象实例的函数参数默认值?
如果我有目标Python 如何更改对象实例的函数参数默认值?,python,python-2.7,class,Python,Python 2.7,Class,如果我有目标 >>> class example_class(): >>> def example_function(number, text = 'I print this: '): >>> print text, number 我可以更改示例函数输入参数 >>> example_instance = example_class() >>> print example_instace
>>> class example_class():
>>> def example_function(number, text = 'I print this: '):
>>> print text, number
我可以更改示例函数输入参数
>>> example_instance = example_class()
>>> print example_instace.example_function(3, text = 'I print that: ')
现在我想总是使用我每次使用示例安装时打印:
。是否可以更改text
的默认值以获得以下行为:
>>> 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
函数默认值与函数一起存储,函数对象用于创建方法包装器。您不能基于每个实例更改该默认值
相反,使用哨兵来检测默认值是否已被选中None
是一个常见的哨兵,适用于None
本身不是有效值的情况:
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.\u example\u text\u default
,即可覆盖
如果None
不是合适的sentinel,请为作业创建唯一的singleton对象:
_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
现在您可以使用example\u class().example\u函数(42,None)
作为有效的非默认值