2015-12-15 23 views
3

我想知道是否有可能創建一個類,無論調用什麼「方法」,總是返回None。Python:使任何函數調用返回None的類

例如,

# The following all returns None 
Myclass.method1() 
Myclass.method2(1, 2, 3) 
Myclass.method2(1,2) 

基本上,我想實現一個類,使得

  1. 任何非內置未由類定義的方法被接受並確認爲有效的方法。
  2. 所有的從點1的方法將返回無

我知道mock.MagicMock可以給我這樣的結果,但它是非常緩慢的,所以我在想,如果那裏有這樣做更好的方法。

回答

6

是的,很容易。

def return_none(*args, **kwargs): 
    """Ignores all arguments and returns None.""" 
    return None 

class MyClass(object): 
    def __getattr__(self, attrname): 
     """Handles lookups of attributes that aren't found through the normal lookup.""" 
     return return_none 
+0

甜,正是我所需要的。謝謝! – user1948847