2015-08-14 101 views
0

如果我有對象如何更改對象實例的函數參數的默認值?

>>> 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: ') 

現在,我想一直使用I print that:我每次使用example_instace時間。是否有可能改變的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 

回答

2

功能默認存儲與函數,函數對象用於創建方法包裝。您無法在每個實例的基礎上更改該默認值。

取而代之的是,使用標記來檢測默認選擇; 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)作爲一個有效的非缺省值。