如何在Python中重写内置的getattr?
我知道如何重写对象的getattr()来处理对未定义对象函数的调用。但是,我希望为内置的getattr()函数实现相同的行为。例如,考虑这样的代码:如何在Python中重写内置的getattr?,python,Python,我知道如何重写对象的getattr()来处理对未定义对象函数的调用。但是,我希望为内置的getattr()函数实现相同的行为。例如,考虑这样的代码: call_some_undefined_function() 通常,这只会产生一个错误: Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'call_some_undefined_func
call_some_undefined_function()
通常,这只会产生一个错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'call_some_undefined_function' is not defined
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
NameError:未定义名称“调用某些未定义的函数”
我想重写getattr(),这样我就可以拦截对“call_some_undefined_function()”的调用,并找出该做什么
这可能吗?我只能想办法通过调用eval来实现这一点
class Global(dict):
def undefined(self, *args, **kargs):
return u'ran undefined'
def __getitem__(self, key):
if dict.has_key(self, key):
return dict.__getitem__(self, key)
return self.undefined
src = """
def foo():
return u'ran foo'
print foo()
print callme(1,2)
"""
code = compile(src, '<no file>', 'exec')
globals = Global()
eval(code, globals)
你还没说你为什么要这么做。我有一个用例,我希望能够处理我在交互式Python会话中犯下的打字错误,所以我将其放入Python启动文件中:
import sys
import re
def nameErrorHandler(type, value, traceback):
if not isinstance(value, NameError):
# Let the normal error handler handle this:
nameErrorHandler.originalExceptHookFunction(type, value, traceback)
name = re.search(r"'(\S+)'", value.message).group(1)
# At this point we know that there was an attempt to use name
# which ended up not being defined anywhere.
# Handle this however you want...
nameErrorHandler.originalExceptHookFunction = sys.excepthook
sys.excepthook = nameErrorHandler
希望这对将来希望为未定义名称提供特殊错误处理程序的人有所帮助。。。这对OP是否有帮助还不清楚,因为他们从来没有告诉我们他们的预期用例是什么。模块对象有一个
\uuuuuu getattribute\uuuuu
方法,但它显然没有被使用。你为什么需要它?ôoI已经尝试覆盖getattribute,但到目前为止还没有成功:Python 2.6b3(r26b3:65922,2008年9月12日,11:22:09)[GCC 3.4.6 20060404(Red Hat 3.4.6-3)]在linux2>>>上定义getattribute(obj,name):。。。打印对象,名称…>>>foo()回溯(最近一次调用last):文件“”,第1行,在NameError中:名称“foo”未定义是的,您将收到一个错误。但是为什么要替换这个函数呢?您有什么可能的新用例?
import sys
import re
def nameErrorHandler(type, value, traceback):
if not isinstance(value, NameError):
# Let the normal error handler handle this:
nameErrorHandler.originalExceptHookFunction(type, value, traceback)
name = re.search(r"'(\S+)'", value.message).group(1)
# At this point we know that there was an attempt to use name
# which ended up not being defined anywhere.
# Handle this however you want...
nameErrorHandler.originalExceptHookFunction = sys.excepthook
sys.excepthook = nameErrorHandler