【问题标题】:How to change default of function parameter for an instance of an object? [duplicate]如何更改对象实例的函数参数的默认值? [复制]
【发布时间】:2015-08-14 15:36:30
【问题描述】:

如果我有对象

>>> class example_class():
>>>    def example_function(number, text = 'I print this: '):
>>>        print text, number

我可以更改 example_function 输入参数

>>> example_instance = example_class()
>>> print example_instace.example_function(3, text = 'I print that: ')

现在我希望每次使用example_instace 时都使用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

【问题讨论】:

    标签: python python-2.7 class


    【解决方案1】:

    函数默认值与函数一起存储,函数对象用于创建方法包装器。您不能在每个实例的基础上更改该默认值。

    相反,使用哨兵来检测是否已选择默认值; 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._example_text_default 即可覆盖。

    如果None 不是合适的哨兵,则为作业创建一个唯一的单例对象:

    _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_class().example_function(42, None) 作为有效的非默认值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-30
      • 1970-01-01
      • 2021-12-19
      • 2023-03-18
      • 2014-08-18
      • 2011-02-23
      • 1970-01-01
      • 2013-01-14
      相关资源
      最近更新 更多