Methods

Jon Reades

Today’s Question

We know that a function looks like this:

<function name>( <input> )

And we know that a function in a package looks like this:

<package name>.<function name>( <input> )

So is list a package?

my_list.append( <value> )

Well…

my_list.append( <value> ) is a function.

my_list.append( <value> ) is a special type of function called a method.

What’s a Method Then?

Packages group useful constants and functions together in one place.

Methods group constants and functions together in one place with data.

So my_list.append(...) is called a list method:

  • It only knows how to append things to lists.
  • It is only available as a function when you have an insantiated list (e.g. [] or [1,'dog',3.5]).
  • It is bound to variables (aka. objects) of class list.

Proof!

my_list = [] 
help(my_list)

This will give you:

Help on list object:

class list(object)
 |  list(iterable=(), /)
 |  Built-in mutable sequence.
 |  If no argument is given, the constructor creates a new empty list.
 |  Methods defined here:
 | ...
 |  append(self, object, /)
 |      Append object to the end of the list.
 |
 |  clear(self, /)
 |      Remove all items from list.
 |
 |  copy(self, /)
 |      Return a shallow copy of the list.
 | ...

It’s all Methods

msg = 'Hello World'
dir(msg)
['__add__', '__class__', ..., 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', ... 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

And then we can inquire about these methods:

help(msg.capitalize)
Help on built-in function capitalize:

capitalize() method of builtins.str instance
    Return a capitalized version of the string.

    More specifically, make the first character have upper case and the rest lower
    case.

Everything in Python is an Object

my_list = [] can also be written my_list = list(), and my_string = 'Foo' can be written my_string = str('Foo').

Final Fundamental Concepts

From here on out, nearly all of what you learn will be new applications, not new concepts and terminology.

Term Means Example
Class The template for a ‘thing’. Recipe for a pizza.
Object The instantiated ‘thing’. A pizza I can eat!
Method Functions defined for the class and available to the object. Things I can do with a pizza (eat, cook, make).
Constructor The special method that builds new objects of that class. How to start a new pizza!
Self A reference to the current object. The pizza in front of me!