This course will become read-only in the near future. Tell us at community.p2pu.org if that is a problem.

Objects [Dec. 21, 2011, 9:15 p.m.]



One of the key aspects of Python is that the language is Object Oriented (OO). The  OO paradigm is a conceptual and organizational methodology that we use to create reusable code and develop applications efficiently. Objects are not inherently complex or difficult to work with, in fact, they are simple to create and re-use throught our programming endeavours. 

Objects have two main characteristics:

  • methods
  • attributes

Methods are another word for functions contained within an object. Attributes are variables within an object. Consider my toaster:

>>> my_toaster = Toaster('shiny', 'crispy')
>>> my_toaster.make_toast(bread)
# returns toast.
>>> my_toaster.color
silver
>>> my_toaster.darkness_setting
crispy

In the first line, I create an instance of the Toaster class (notice the capital T in Toaster) and assign it to 'my_toaster'. I tell the Toaster class that my_toaster is shiny and makes crispy toast. Afterwords, I can interact with my_toaster by accessing its methods (functions) and attributes (variables).

Notice that the function and attributes are accessed by appending a dot ('.') and the relevant name/function call. This is called, appropriately, 'dot notation' and is designed as a convenience for us programmers.