2010-06-16 46 views
3

我知道如何覆蓋對象的getattr()來處理對未定義對象函數的調用。但是,我想爲內置的getattr()函數實現相同的行爲。例如,考慮這樣的代碼:如何覆蓋Python中的內置getattr?

call_some_undefined_function() 

通常情況下,簡單地產生一個錯誤:

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
NameError: name 'call_some_undefined_function' is not defined 

我要重寫GETATTR(),這樣我可以攔截調用「call_some_undefined_function()」並弄清楚該怎麼做。

這可能嗎?

+0

模塊對象有一個'__getattribute__'方法,但它顯然沒有被使用。 – Omnifarious 2010-06-16 16:30:39

+2

一個問題:爲什麼? – 2010-06-16 16:35:30

+1

你需要什麼? OO – Joschua 2010-06-16 16:59:20

回答

2

我只能想辦法通過調用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) 

上述輸出

ran foo 
ran undefined 
0

爲什麼你要做到這一點你沒有說。我曾在那裏我想成爲能夠處理我在交互式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是否有用是未知的,因爲它們從未實際告訴我們它們的用途是什麼。