簡體   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