__getattr__ em um módulo
Como implementar o equivalente a um__getattr__
em uma aula, em um módulo?
Ao chamar uma função que não existe nos atributos estaticamente definidos de um módulo, desejo criar uma instância de uma classe nesse módulo e chamar o método nele com o mesmo nome que falhou na pesquisa de atributo no módulo.
class A(object):
def salutation(self, accusative):
print "hello", accusative
# note this function is intentionally on the module, and not the class above
def __getattr__(mod, name):
return getattr(A(), name)
if __name__ == "__main__":
# i hope here to have my __getattr__ function above invoked, since
# salutation does not exist in the current namespace
salutation("world")
Que dá:
matt@stanley:~/Desktop$ python getattrmod.py
Traceback (most recent call last):
File "getattrmod.py", line 9, in <module>
salutation("world")
NameError: name 'salutation' is not defined