简体   繁体   English

使用__getattr__防止方法被调用

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

I am trying to prevent an instance from throwing an exception if a method that does not exist for the instance is called. 我试图阻止实例在调用实例不存在的方法时抛出异常。 I have tried the following: 我尝试过以下方法:

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()

The problem is that I get the following error: 问题是我收到以下错误:

TypeError: 'NoneType' object is not callable

The two things I want to make sure of doing is: 我想确保做的两件事是:

  1. Return None as my code can deal with variables being set to None 返回None因为我的代码可以处理设置为None变量
  2. Perform a function (printing a warning message) 执行功能(打印警告信息)

What is the cleanest way to do this? 最干净的方法是什么?

return a function that does nothing? 返回一个什么都不做的函数?

Couple of things: first you might want to use __getattr__ rather than __getattribute__ . 几件事:首先你可能想要使用__getattr__而不是__getattribute__
__getattr__ gets called when the runtime doesn't find anything by that name in the hierarchy, __getattribute__ gets called every time. __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

Your __getattr__ is the same as: 你的__getattr__与以下内容相同:

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

So, when you do var = o.someNonExistantFunction() , this is logically the same as: 因此,当你执行var = o.someNonExistantFunction() ,这在逻辑上与以下相同:

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

Which is why you're getting the NoneType not callable error. 这就是为什么你得到NoneType不可调用的错误。 Obtuse definitely has the rest of the answer, which is to return a callable function. Obtuse肯定有其余的答案,即返回一个可调用的函数。 However, you might think about other structural issues, and if it's truly a good idea to have a catchall function generator. 但是,您可能会考虑其他结构问题,如果拥有一个catchall函数生成器真的是个好主意。

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

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