Objects [Dec. 21, 2011, 9:57 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.
So, creating an instance of a class seems easy, right? Lets cover the basics of creating a class. We will go ahead and peer inside the Toaster class.
class Toaster: """Found in kitchens around the world. Excellent for toasting bread.""" def __init__(self, color, darkness_setting): self.color = color self.darkness_setting = darkness_setting def make_toast(bread): # Code to make toast return toast
The first line above is the class definition. The word class preceeds the name (uppercase as a convention) and a colon. The following line is a documentation string, giving further details about the toaster class.