# Overload.py Copyright (c) Kari Laitinen # http://www.naturalprogramming.com # 2006-05-23 File created. # 2022-12-16 Converted to Python 3. # The corresponding Java/C++/C# programs (e.g. Overload.java) # demonstrate the method (function) overloading mechanism in # those languages. Because function overloading is not possible # in Python, this program demonstrates how it is possible to # circumvent the absence of method overloading in Python # programs. # In the Java/C++/C# languages method overloading means that # different methods can have the same name when they take a # different set of parameters (arguments). # In Python we can write functions (methods) that inspect the # types of given arguments and behave in different ways according # to the types. Python has a built-in function named isinstance() # that can be used to check whether a data item has a certain # type. # This program contains a single function named print_list() # that can perform the job of the three print_array() functions # in the corresponding Java/C++/C# programs. # In Python there is no type char. Characters in Python programs # are one-character strings. def print_list( given_list, number_of_items_to_print = -1 ) : if len( given_list ) == 0 : print( "\n\n Empty lists cannot be printed.", end="" ) elif isinstance( given_list[ 0 ], int ) : print( "\n\n Integers in list:", end="" ) for integer_index in range( number_of_items_to_print ) : print( " %d" % given_list[ integer_index ], end="" ) elif isinstance( given_list[ 0 ], str ) : if ( number_of_items_to_print != -1 ) : print( "\n\n Characters in list:", end="" ) for character_index in range( number_of_items_to_print ) : print( " %c" % given_list[ character_index ], end="" ) else : # The parameter value -1 means that the whole list will be printed. print( "\n\n Characters in list:", end="" ) for character_in_list in given_list : print( " %c" % character_in_list, end="" ) else : print( "\n\n Type %s not supported by function print_list()" % \ type( given_list[ 0 ] ), end="" ) first_list = [ 55, 77, 888, 4444, 33, 22, 11 ] second_list = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H' ] print_list( first_list, 6 ) print_list( second_list ) print_list( second_list, 5 ) empty_list = [] list_of_floats = [ 77.77, 88.88, 99.99, 111.111 ] print_list( empty_list ) print_list( list_of_floats ) print( "\n\n In Python lists can be printed with the print function:" ) print( empty_list ) print( list_of_floats )