Python在实例的基中寻找特殊的方法,如__getattr____dict__s,不在实例的__dict__中。在
self.tool是一个类。self.tool.test,因此,将调用self.tool的类的__getattr__(它是{}),这不是我们想要的。在
相反,让self.tool成为一个实例,它的类有一个__getattr__:class Foo(object):
def __init__(self):
self.NameList=[]
# add new class to ourself
toolcls = type('tool', (object,), { '__getattr__' : self.__getattr__, } )
self.tool = toolcls()
self.NameList.append( "test" )
# should be called by our newly added "tool" object but is only called sometimes...
def __getattr__(self, attr):
# print("__getattr__: (%s, %s)" % (self.__class__.__name__, attr) )
if( attr in self.NameList ):
return( 99 )
raise AttributeError(" %r object has no attribute %r" % (
type(self).__name__, attr))
foo = Foo()
print( "foo.tool.__getattr__=%d" % foo.tool.__getattr__("test") )
print( "foo.tool.test=%d" % foo.tool.test )
收益率
^{pr2}$
另外,请注意,如果生成Foo的实例而没有定义self.NameList,则上述代码可能导致无限递归。见Ned Batchelder's post on this suprising pitfall。在
为了防止此处出现无限递归,请使用def __getattr__(self, attr):
# print("__getattr__: (%s, %s)" % (self.__class__.__name__, attr) )
if attr == 'NameList':
raise AttributeError()
if( attr in self.NameList ):
return( 99 )
raise AttributeError(" %r object has no attribute %r" % (
type(self).__name__, attr))