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)
基本上,我想实现一个类,这样
我知道这mock.MagicMock可以给我这个结果,但它很慢,所以我想知道是否有更好的方法来做到这一点.
是的,很容易.
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)