【问题标题】:Python: making a class that return None on any function callsPython:创建一个在任何函数调用上都返回 None 的类
【发布时间】:2015-12-15 23:12:31
【问题描述】:

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

例如,

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

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

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

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

【问题讨论】:

    标签: python function class


    【解决方案1】:

    是的,很简单。

    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
    

    【讨论】:

    • 甜蜜,正是我需要的。谢谢!
    猜你喜欢
    • 2020-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-14
    • 2011-02-13
    相关资源
    最近更新 更多