Dictionaries and Classes - Runpython-IntroProgramming/Course-Syllabus GitHub Wiki

Python has many features designed to simplify the job of organizing, storing and working with data. Two of these which are especially important are dictionaries and classes.

Dictionaries

One thing that Python (and computers, generally) excels at is handling information. You have had some experience managing information using variables and lists, but there is much more that Python can help you with. One way of managing information is using the dictionary. Following is an example of defining and using a dictionary with the Python console:

>>> ages = {'fred':9, 'bob':39, 'sally':19}
>>> print(ages['fred'])  # now you can access the ages by name
9
>>> # and you can add new people and ages by just assigning them
>>> ages['jeremy'] = 13  
>>> print(ages['jeremy'])
13
>>> # retrieve a key, but specify a default value in case the 
>>> # the key isn't found
>>> print(ages.get('zachary', 0))  
0

A dictionary is an object that lets you associate a key with some data (or value). Just like a real (paper) dictionary associates words with their corresponding definitions. In the example above the key is the person's name, and the value is their age.

You can work with all the keys in a dictionary using a for loop (sort of like looping through items in a list) and you can obtain a list of key/value pairs in a dictionary using the items method of the dictionary. Items in a dictionary are not sorted in any way and you can not depend on a for loop with a dictionary to return the keys in any order.

The keys used in the example above were strings. Dictionary keys can not be just anything. They have to be immutable. Immutable objects in Python are those which can not be changed after they are created. Strings, for example, are immutable. There are many methods on string objects, but none of them modify the string they are called with (they may return a new string, however). Other common immutable objects in Python are tuples and numbers (which makes these types of objects suitable as dictionary keys).

The values stored in a dictionary can be any kind of object in Python. For example, you can store other objects (including dictionaries, if you are that crazy), classes and functions.

Arrays in Python

If you are used to writing programs in another language (such as C/C++ or Java) you may be wondering how to define arrays in Python. In practice, arrays are often used merely as a structure for collecting objects or values of some type (and in many languages, all the items must be the same type). In Python, there are many different types of collections and one of them is usually an appropriate substitute for a typical application of the C/C++/Java array. For example, tuples, lists or dictionaries can be used for many of the situations where an array is used in C/C++/Java.

Having said that, there is an array type in Python that you can access by using the import array statement. Like a C/C++/Java array, it is restricted to a single type and is not as flexible as the "standard" Python collection types.

Classes (or "object blueprints")

Up to now you have been working with objects without even thinking about it. For example, if you create a list:

>>> l = ['z','b','c']  # here is the list object: l
>>> l.sort()        # use a method (sort) on the object (l)
>>> print(l)        # get its value 
['b', 'c', 'z']

You can create your own types of objects. The name for a type of object is class. A class is like a blueprint for creating an object. You can create many objects from one blueprint. Here is an example of a class that represents a 3 dimensional box:

class Box3D(object):
    def __init__(self, width, length, height):
        self.w = width
        self.l = length
        self.h = height

    def volume(self):
        return self.w * self.l * self.h

And here is an example of how you would use the Box3D class:

box = Box3D(1,3,6)    # create a box object using the 
                      # Box3D class or "blueprint"
box2 = Box3D(3,6,2)   # create another, different object 
                      # using the same class
print(box.volume())
print(box2.volume())  # volume() is a method of the Box3D class
print(box.h)          # you can access the members
box.h = 99.0          # and you can change them
print(box.volume())   # and it will change the box properties

This short program would produce the following output:

18
36
6
297.0

Structure of a Class Definition

class

The class definition begins with the class statement, the name of the class followed (in parentheses) by the name of a class (if any) that it is based on. If you create a new class definition based on an older one, your new class inherits all of the methods and members of the original class. This is a powerful tool for extending existing code with new functionality.

__init__ or Initialization Method

All classes must define an initializer method called __init__ that Python will call to help set up your new objects. The initializer can have zero or more arguments that are used to define the behavior of the object. All methods for the class must also include a first argument called self. In your class definitions, self refers to the object that you are creating. By adding attributes to self in the __init__ function you can have information "stick" to the object you created. For example, the __init__ function of the Box3D class saves the width, height and depth to member variables w, l and h.

Attributes

Variables that you create beginning with self (e.g. self.w, etc.) are known as object attributes. The attributes you create in the __init__ method can be accessed from any other method of the class using the self.<name> syntax (e.g. self.w).

As you can see from the example above, attributes may also be accessed from outside the class definition by using the name of the object (box and box2 in the example above), period, then the name of the attribute (e.g. box.h).

def: Object Methods

You can add methods to your classes. For example (above), the Box3D class includes a method for calculating the volume of the box. A method is similar to an ordinary Python function, with the exception that it is attached to the object (and its data). In this way Python classes encapsulate all of the information and functions required for a particular type of object.

Notice that all of the methods that you define in a class must be indented, relative to the first class statement. Each method definition begins with the keyword def, followed by the method name and a list of parameters (beginning with self) that the method requires (inside parentheses). Finally, each def statement must end with a colon, and the code inside the method must be indented again.

When you call methods of an object, you use the name of the object (e.g. box), a period, then the name of the method with parentheses and (optionally) arguments (e.g. box.volume()). Notice that calling the volume method of the Box3D class you don't supply the argument for the self parameter.


Questions

  1. When specifying colors with numeric codes, red is 0xff000, green is 0x00ff00, and blue is 0x0000ff. Write code to create a dictionary where 'red', 'green' and 'blue' are the keys and the codes above are the values.
  2. With your answer to (1), write a line of code that would retrieve the color code for green using your dictionary.
  3. With your answer to (1), write a line of code that would return the color code for black (0x000000 or just 0) when using a key that isn't in the dictionary.
  4. With your answer to (1), write a line of code that adds the color code for black to your dictionary.
  5. Write code for a class called Circle that creates a circle object using the radius as an input parameter (e.g. c = Circle(2)) and has a single method for computing the area of the circle (e.g. c.area()).
⚠️ **GitHub.com Fallback** ⚠️