Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何更改对象实例的函数参数默认值?_Python_Python 2.7_Class - Fatal编程技术网

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)
作为有效的非默认值