繁体   English   中英

使用__getattr__防止方法被调用

[英]Prevent a method from being called if it is incorrect using __getattr__

我试图阻止实例在调用实例不存在的方法时抛出异常。 我尝试过以下方法:

class myClass(object):
    def __init__(self):
        pass
    def __getattr__(self,name):
        print "Warning - method {0} does not exist for this instance".format(name)

o = myClass()
var = o.someNonExistantFunction()

问题是我收到以下错误:

TypeError: 'NoneType' object is not callable

我想确保做的两件事是:

  1. 返回None因为我的代码可以处理设置为None变量
  2. 执行功能(打印警告信息)

最干净的方法是什么?

返回一个什么都不做的函数?

几件事:首先你可能想要使用__getattr__而不是__getattribute__
__getattr__被调用时,运行时不会在层次结构中找到这个名字什么, __getattribute__被称为每次。

class Test(object):
    def __getattr__(self,key):
        def placeholder(*args, **kwargs):
            print "Warning - method '%s' does not exist for this instance"%key
        return placeholder

你的__getattr__与以下内容相同:

def __getattr__(self, name):
    print "Warning ..."
    return None

因此,当你执行var = o.someNonExistantFunction() ,这在逻辑上与以下相同:

var = o.someNonExistantFunction # == o.__getattr__('someNonExistantFunction') == None
var() # same as (None)()

这就是为什么你得到NoneType不可调用的错误。 Obtuse肯定有其余的答案,即返回一个可调用的函数。 但是,您可能会考虑其他结构问题,如果拥有一个catchall函数生成器真的是个好主意。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM