ThisClark
ThisClark

Reputation: 14823

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

Upvotes: 1

Views: 861

Answers (3)

GingerPlusPlus
GingerPlusPlus

Reputation: 5626

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)

Upvotes: 1

user2357112
user2357112

Reputation: 281519

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.

Upvotes: 1

juanchopanza
juanchopanza

Reputation: 227468

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.

Upvotes: 3

Related Questions