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

3

我想知道是否可以创建一个类,无论调用什么“方法”,始终返回None。

例如:

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

基本上,我想实现一个类,使得:

  1. 任何非内置方法,只要未被该类定义,都可以被接受并识别为有效方法。
  2. 所有来自点1的方法都将返回None。

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

1个回答

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

太好了,正是我需要的。谢谢! - user1948847

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接