我试图防止实例在调用实例不存在的方法时抛出异常。我尝试了以下方法:
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
我想确保做的两件事是:
- 返回
None
因为我的代码可以处理设置为None
的变量 - 执行功能(打印警告消息)
最干净的方法是什么?
最佳答案
返回一个什么都不做的函数?
一些事情:首先你可能想使用 __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
关于python - 使用 __getattr__ 防止调用不正确的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8813042/