Skip to main content
Engineering LibreTexts

2.08: A Reminder About Functions, Methods, Constructor Functions, and Functions in Modules (and the Difference Between Them)

  • Page ID
    14416
  • Functions and methods are almost the same thing. They can both be called to execute the code in them. The difference between a function and a method is that a method will always be attached to an object. Usually methods change something about that particular object (you can think of the attached object as a sort of permanent argument passed to the method).

    This is a function call of a function named foo():

    foo()

    This is a method call of a method also named foo(), which is attached to an object stored in a variable named duckie:

    duckie.foo()

    A call to a function inside of a module may look like a method call. To tell the difference, you need to look at the first name and see if it is the name of a module or the name of a variable that contains an object. You can tell that sys.exit() is a call to function inside of a module, because at the top of the program will be an import statement like import sys.

    A constructor function is the same thing as a normal function call, except that its return value is a new object. Just by looking at source code, a function and constructor function look the same. Constructor functions (also called simply a "constructor" or sometimes "ctor" ("see-tor") for short) are just a name given to functions that return a new object. But usually ctors start with a capital letter. This is why when you write your own programs, your function names should only begin with a lowercase letter.

    For example, pygame.Rect() and pygame.Surface() are both constructor functions inside the pygame module that return new Rect and Surface objects. (These objects are described later.)

    Here’s an example of a function call, a method call, and a call to a function inside a module:

    import whammy
    fizzy()
    egg = Wombat()
    egg.bluhbluh()
    whammy.spam()
    

    Even though these names are all made up, you can tell which is a function call, a method call, and a call to a function inside a method. The name whammy refers to a module, since you can see it is being imported on the first line. The fizzy name has nothing before it and parentheses after it, so you know it is a function call.

    Wombat() is also a function call, in this case it is a constructor function that returns an object. (The capital letter that it starts with isn’t a guarantee that it’s a constructor function rather than a regular function, but it is a safe bet.) The object is stored in a variable named egg. The egg.bluhbluh() call is a method call, which you can tell because bluhbluh is attached to a variable with an object in it.

    Meanwhile, whammy.spam() is a function call, not a method call. You can tell it is not a method because the name whammy was imported as a module earlier.