简体   繁体   English

Python中一个function参数名称与另一个function相同的问题如何处理?

[英]How to deal with the problem that a function parameter name is the same as another function in Python?

Here is an example:这是一个例子:

def clean_datetime(x):
    return x

def func(clean_datetime = True):
    if clean_datetime:
        return clean_datetime(1)
        
func(True)

This will return an error TypeError: 'bool' object is not callable .这将返回错误TypeError: 'bool' object is not callable Is there a way I don't need to change the function parameter name?有没有办法我不需要更改 function 参数名称?

Technically, you could pull the function out of globals() , but this is a terrible, terrible thing to do compared to just renaming the function or the parameter.从技术上讲,您可以将 function 拉出globals() ,但与仅重命名 function 或参数相比,这是一件可怕的事情。

In [53]: def clean_datetime(x):
    ...:     return x
    ...:
    ...: def func(clean_datetime = True):
    ...:     if clean_datetime:
    ...:         return globals()['clean_datetime'](1)
    ...:
    ...: func(True)
Out[53]: 1

Like already suggested in the comments changing the function name or parameter name is a better option IMO.就像评论中已经建议的那样,更改 function 名称或参数名称是 IMO 更好的选择。 It makes the code less ambiguous.它使代码不那么模棱两可。

A workaround is to create an alias for the function or create a function that calls the necessary function.一种解决方法是为 function 创建一个别名,或创建一个调用必要的 function 的 function。

def clean_datetime(x):
    return x

alias = clean_datetime

def func(clean_datetime = True):
    if clean_datetime:
        return alias(1) # Calls clean_datetime(1)
        
func(True) # Returns 1

there is the only one way: you need to change the function name or parameter name只有一种方法:您需要更改 function 名称或参数名称

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM