Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

python getattr built-in method executes default arguments

I dont know if this is something an expected behavior of getattr built_in method. getattr executes the default(3rd) argument as well even if the actual argument(2nd) satisfies the condition. Example:

def func():
    print('In Function')

class A:
    def __init__(self):
        self.param = 12

a = A()

When I run getattr(a, 'param', func()) it gives this result:

In Function
12

Note the In Function which I don't want.

But it works perfectly fine when I execute getattr(a, 'param1', func()) i.e output

In Function

But I only want result as 12 if satisfied the condition. Please let me know why getattr has such behaviour and can we stop them of doing it (that is not to execute 3rd arg if has 2nd argument), would be appreciated if share the alternate way of doing it in Pythonic way. One thing that comes in mind first is to check if param1 exist using hasattr and then do the needful.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...