Generic function

From CS 61A Wiki
Revision as of 09:43, 23 July 2014 by Kim (Talk | contribs)

Jump to: navigation, search

A generic function is a function that can take in different object types and operate on all of them. This is especially helpful when the objects we are working with have multiple representations. A good example is the variety of number representations we learned in lecture.

Creating a generic function

The following techniques are convenient ways to create a generic function:

Type dispatching

Type dispatching does exactly as its name suggests: depending on the type of the arguments passed in, the function will proceed in different ways. This is especially convenient because it means you can create a general function that will work for a variety of different things.

example: a drive function

Consider the following drive function, which takes in a variety of car types and returns the correct drive method depending on the type given.

def drive(car):
    if type(car) == SportsCar:
        return car.drive_sportscar()    elif type(car) == Van:
        return car.drive_van()
    elif type(car) == SemiTruck:
        return car.drive_semitruck()
    elif type(car) == Tractor:
        return car.drive_tractor()


Another way of implementing generic functions is through coercion, which is simply converting our original object into a new type of object so that we can use the new object's methods. This is especially helpful when the two different objects have some similar properties, and when our original object can be seen as a the new type with certain modifications.

example: a function


CS61A Su14 Lecture 17

CS61A Su14 Discussion 9

CS61A Fa11 2.7.3