English

Predict the output of the following program. Also state which concept of OOP is being implemented? def sum(x, y, z): print "sum= ", x+y+zdef sum(a, b): print "sum= ", a+bsum(10, 20) sum(10, 20, 30)

Advertisements
Advertisements

Question

Predict the output of the following program. Also state which concept of OOP is being implemented?

def sum(x, y, z):
        print "sum= ", x+y+z
def sum(a, b):
       print "sum= ", a+b
sum(10, 20)
sum(10, 20, 30)

Code Writing
Advertisements

Solution

Python 3 update: print "..." must be written as print("...").

Trace:

  1. The second definition of sum(a, b) overwrites sum(x, y, z).
  2. Therefore, sum(10, 20) prints the sum of two values.
  3. sum(10, 20, 30) causes an error because the active definition accepts only two arguments.
sum=  30
TypeError: sum() takes 2 positional arguments but 3 were given

The program attempts to implement function overloading, a form of polymorphism, but Python does not support it through repeated function definitions.

shaalaa.com
  Is there an error in this question or solution?
Chapter 2: Concept of Object Oriented Programming - EXCERCISE [Page 37]

APPEARS IN

CBSE Computer Science with Python [English] Class 12
Chapter 2 Concept of Object Oriented Programming
EXCERCISE | Q 13. | Page 37
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×