python getattr built-in method executes default arguments

我们两清 提交于 2019-12-01 21:29:28
Moses Koledoye

Before getattr gets executed, all the passed parameters have to be evaluated. func() is one of those parameters and an attempt to evaluate it will execute the print statement. Whether the attribute will be found or not, func() must be evaluated apriori.

This isn't peculiar to getattr, it's how functions and their parameters work in Python.


Consider the following:

>>> def does_nothing(any_arg): pass
...
>>> def f(): print("I'll get printed")
...
>>>
>>> does_nothing(f())
I'll get printed

Function does_nothing actually does nothing with the passed parameter. But the parameter has to be evaluated before the function call can go through.


The print statement however will not affect the outcome of getattr; sort of a side effect. In the event the attribute is not found the return value of the function is used.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!