简体   繁体   中英

if Python doesn't support method overloading, then why does this method overload work while this other does not?

If Python does not support method overloading (besides *args and **kwargs or PEP 3124 ), then why does this overload work?

# the sum from 1 to n
def sum(n):
    if n > 0:
        return n + sum(n - 1)
    else:
        return 0

print(sum(3))

# the sum from n to m, inclusive
def sum(n, m):
    if n <= m:
        return n + sum(n + 1, m)
    else:
        return 0

print(sum(3,5))

... while more baffling, this one does not:

# the sum of elements in an array
def sumArray(A):
    return sumArray(A, len(A)-1)

# a helper for the above
def sumArray(A, i):
    if i < 0:
        return 0
    else:
        return A[i] + sumArray(A, i-1)

print(sumArray([1,2,3]))

You aren't overloading. You're hiding one thing behind another by using the same name for different objects. Try

sum = 42

and see how print(sum(3, 5)) ceases to work.

In your first example, you define function and use it, then overwrite it with another, and use the new one, just like with regular variables:

a = 1
print(a)

a = 2
print(a)

Function definitions are variable assignments. They create a function and assign it to the variable matching the name you used. You're seeing the ordinary effects of reassigning a variable.

def sum(n):
    ...

This assigns a function of 1 argument to the variable sum .

print(sum(3))

This uses the function assigned to that variable.

def sum(n, m):
    ...

This assigns a new function to the variable sum , replacing the first function.

print(sum(3,5))

This uses the new function. If you had tried to use the old function, you wouldn't find it.


# the sum of elements in an array
def sumArray(A):
    return sumArray(A, len(A)-1)

# a helper for the above
def sumArray(A, i):
    if i < 0:
        return 0
    else:
        return A[i] + sumArray(A, i-1)

print(sumArray([1,2,3]))

This assigns a function to sumArray , then assigns a different function to sumArray , then tries to use the value from the first assignment. It finds the second function, and fails.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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