python getattr内置方法执行默认参数 [英] python getattr built-in method executes default arguments

查看:80
本文介绍了python getattr内置方法执行默认参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道这是否是getattr Built_in方法的预期行为. 即使实际参数(2nd)满足条件,getattr也会执行default(3rd)参数. 示例:

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()

当我运行getattr(a, 'param', func())时,它会给出以下结果:

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

In Function
12

注意我不想要的In Function.

但是当我执行getattr(a, 'param1', func())即输出时,它工作得很好

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

In Function

但是如果满足条件,我只希望结果为12.请让我知道为什么getattr具有这种行为,我们能否阻止他们这样做(如果有第二个参数,则不执行第3个arg),如果以Pythonic方式共享它的另一种选择,将不胜感激. 首先想到的一件事是使用hasattr检查param1是否存在,然后做有需要的事情.

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.

推荐答案

在执行getattr之前,必须评估所有传递的参数. func()是这些参数之一,尝试对其进行评估将执行print语句.无论是否找到该属性,必须先对func()进行评估.

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.

这不是getattr所特有的,这是函数及其参数在Python中的工作方式.

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

请考虑以下内容:

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

函数does_nothing实际上对传递的参数不执行任何操作.但是必须在函数调用通过之前对参数进行求值.

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

print语句不会影响getattr的结果;一种副作用.如果找不到该属性,则使用该函数的return值.

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.

这篇关于python getattr内置方法执行默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆