Python:在任何函数调用中创建一个返回None的类

use*_*847 3 python class function

我想知道是否有可能创建一个类,无论调用什么"方法",总是返回None.

例如,

# The following all returns None
Myclass.method1()
Myclass.method2(1, 2, 3)
Myclass.method2(1,2) 
Run Code Online (Sandbox Code Playgroud)

基本上,我想实现一个类,这样

  1. 任何未由类定义的非内置方法都被接受并被识别为有效方法.
  2. 第1点的所有方法都将返回None

我知道这mock.MagicMock可以给我这个结果,但它很慢,所以我想知道是否有更好的方法来做到这一点.

use*_*ica 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
Run Code Online (Sandbox Code Playgroud)