[英]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
我想確保做的兩件事是:
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
你的__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.