Is it a bad idea to declare a function that has the same name as a method?

In this example set has the method union and I have also declared a function called union:

def union(*lists):
    '''returns a list containing all unique values from input lists'''

    if len(lists) == 0:
        return lists[0]

    result = lists[0]
    for item in range(1, len(lists)):
        result = set(result).union(set(lists[item]))

    return list(result)    

a=[1,2,4]
b=[4,5,1]
c=[9,7,5]

print union(a, b, c)

I looked at PEP8 and found that methods and functions have the same naming rules, but is it OK to give them the same name?

有帮助吗?

解决方案

There is no problem using names that also are used as methods on some objects. Different namespaces won't conflict.

The only thing you need to worry about are masking names in the same namespace; built-ins are global, globals are visible in the local namespace, so you don't want to mask built-in names.

But methods on an object are only visible to that scope; you need to qualify the method with someset.union(), which can never conflict with your union() function.

If you did have to restrict your names to anything that is not already taken by a method in the Python standard library, you would have scarcely have any names left to use.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top