Concepts / Creating Your Own Classes and Objects

Creating Your Own Classes and Objects

Object-oriented programming centers on the idea that objects combine data with the actions they can perform. Lists provide a familiar example of this idea.

  • Programming

A List Is More Than a Container

A list is an object. It bundles together the data it contains, such as its items, and the behaviors it can perform, such as adding an item, sorting its contents, or retrieving an item. When you create a list, you are creating an object with both data and actions.

list objectitemsdataappend()add an itemsort()rearrange items__getitem__()retrieve an itemcontainsprovidesprovidesprovides
What data does a list object contain, and what methods operate on that data?
Key point

Object-oriented programming centers on the idea that objects combine data with the actions they can perform. Lists provide a familiar example of this idea.

Watching List State Change

A list is mutable, which means its contents can change after the list is created. The append() method adds an item to the end of the list. The sort() method rearranges the existing items in order. Both methods modify the list object in place.

['zebra', 'ant']initial list['zebra', 'ant','python']after append()['ant', 'python','zebra']after sort()append('python')sort()
What does the list contain before and after calling append() and sort(), and how does its state change step by step?
Worked example

Following Two List Methods

Trace the list after it is created, after append('python'), and after sort().

  1. 1
    Initial state

    The list begins with the items 'zebra' and 'ant'.

  2. 2
    Append

    append('python') adds 'python' to the end, so the list now contains three items.

  3. 3
    Sort

    sort() rearranges the strings alphabetically, placing 'ant' first, 'python' second, and 'zebra' third.

Result

The final list is ['ant', 'python', 'zebra'].

Code walkthrough
stuff = list()
stuff.append('zebra')
stuff.append('ant')
stuff.append('python')
stuff.sort()
print(stuff)
  1. 1
    The name stuff refers to a newly constructed list object.
  2. 2
    The first append() call adds 'zebra'.
  3. 3
    The second append() call adds 'ant' after 'zebra'.
  4. 4
    The third append() call adds 'python' after 'ant'.
  5. 5
    sort() changes the order of the items alphabetically.
  6. 6
    The final list is displayed.
  • list() constructs a list object.
  • Each append() call adds one item to the end of the list.
  • sort() rearranges the strings alphabetically.
  • print() displays the list after the changes.
Output
['ant', 'python', 'zebra']

Methods as Object Behaviors

A method is an action or behavior that an object can perform. In stuff.append('python'), append() is being called on the list object referred to by stuff. The method changes that object's contents by adding a new item at the end.

In stuff.sort(), sort() is also called on the list object. Instead of adding an item, it rearranges the items into order. For strings, the source explains this as alphabetical order; for numbers, it is numerical order.

method callstuff.append('python')append()add to endupdated listone more iteminvokesmodifies
How does control move from a list method call to the resulting change in the list contents?

Three Ways to Retrieve an Item

A list item can be retrieved with square bracket syntax or with the list's __getitem__() method. The source presents three equivalent forms for retrieving the item at position 0: stuff[0], stuff.__getitem__(0), and list.__getitem__(stuff, 0).

stuff[0]position 0first itemsame resultstuff.__getitem__(0)position 0list.__getitem__(stuff,0)position 0retrievesretrievesretrieves
How do the three retrieval forms map to the same item position?
python
FormWhat it showsRecommended use
stuff[0]Retrieves the item at position 0Standard and most convenient syntax
stuff.__getitem__(0)Calls the special method directly on the list objectMore explicit view of the list behavior
list.__getitem__(stuff, 0)Calls the method on the list class and passes stuff as the first parameterMost verbose form

All three forms retrieve the same item at position 0.

Positions and Retrieved Items

The number inside square brackets identifies the position of the item to retrieve. In the source example, position 0 means the first item. __getitem__(0) performs the same retrieval when called explicitly, so the index and the returned item remain connected across all three syntaxes.

0indexfirst itemposition 0retrieved item__getitem__(0)selectsreturns
How does a numeric index identify a specific item inside a list, and what does __getitem__() return?

Mistakes Beginners Make

  • Common mistake

    Treating a list as only passive data

    What it looks like

    Thinking of stuff as merely a container and overlooking append(), sort(), and __getitem__().

    Why it fails

    A list bundles its items with behaviors that operate on those items.

    Do this instead

    When reading list code, identify both the current data and the method being called.

  • Common mistake

    Forgetting that append() changes the list

    What it looks like

    Tracing the program as though stuff still has the same number of items after stuff.append('python').

    Why it fails

    append() adds an item to the end and modifies the list in place.

    Do this instead

    Record the list's new contents immediately after the append() call.

  • Common mistake

    Expecting sort() to leave the order unchanged

    What it looks like

    Assuming the list keeps its insertion order after stuff.sort().

    Why it fails

    sort() rearranges the items into order.

    Do this instead

    Trace the list again after sorting; strings are arranged alphabetically and numbers numerically.

  • Common mistake

    Assuming the explicit retrieval forms produce different items

    What it looks like

    Treating stuff[0], stuff.__getitem__(0), and list.__getitem__(stuff, 0) as three different retrieval operations.

    Why it fails

    All three forms retrieve the item at position 0.

    Do this instead

    Recognize square brackets as the standard, convenient syntax for the same behavior.

Check Your Understanding

What do you think happens?

A list starts as ['zebra', 'ant']. After append('python') and then sort(), what will the final list contain?

  • ['zebra', 'ant', 'python']

  • ['ant', 'python', 'zebra']

  • ['python', 'ant', 'zebra']

Reveal answer
Answer:

['ant', 'python', 'zebra']

append() first adds 'python' to the end. sort() then rearranges the strings alphabetically.

EASY

For a list named stuff, write the three equivalent expressions that retrieve the item at position 0. Then explain which form is normally preferred and why.

Hints
  • Start with square bracket syntax.
  • Use __getitem__() as a method on stuff.
  • For the most verbose form, call __getitem__() on list and pass stuff as the first parameter.

From Built-In Objects to Your Own

Lists make object-oriented programming concrete. The list's items are its data, while append(), sort(), and __getitem__() are behaviors available through the list object. Method calls can modify the object in place, as append() and sort() do. Item retrieval can be written with square brackets or with the corresponding __getitem__() forms, but square brackets are the standard choice. This perspective prepares you to create objects with your own data and methods.

Key Takeaways

  • A list is an object that combines its item data with methods that operate on that data.
  • append() adds an item to the end of a list, while sort() rearranges items in order.
  • append() and sort() modify the existing list object in place.
  • stuff[0], stuff.__getitem__(0), and list.__getitem__(stuff, 0) retrieve the same item at position 0.
  • Understanding lists as objects provides a foundation for creating objects with custom data and methods.

Related concepts

More concepts starting with C