The Web Page
of the Book of
the Web page
Although, as the book states, the details of this example are explained later, some readers have found difficulty getting the example as shown to work. This note gives a line by line explanation of the code:
The complete code for the example looks like this:
>>> class Address: ... def __init__(self, Hs, St, Town, Zip): ... self.Hs_Number = Hs ... self.Street = St ... self.Town = Town ... self.Zip_Code = Zip ... >>> Addr = Address(7,"High St","Anytown","123 456") >>> print Addr.Hs_Number, Addr.Street
Here is the explanation:
>>> class Address:
The class statement tells Python that we are about to define a new type called, in this case, Address. The colon indicates that any indented lines following will be part of the class definition. The definition will end at the next unindented line. If you are using IDLE you should find that the editor has indented the next line for you, if working at a command line Python prompt in an MS DOS window then you will need to manually indent the lines as shown. Python doesn't care how much you indent by, just so long as it is consistent.
... def __init__(self, Hs, St, Town, Zip):
The first item within our class is what is known as a method definition. This method is called __init__ and is a special operation performed by Python when we create an instance of our new class, we'll see that shortly. The colon, as before, simply tells Python that the next set of indented lines will be the actual definition of the method.
... self.Hs_Number = Hs
This line plus the next three, all assign values to the internal fields of our object. They are indented from the def statement to tell Python that they constitute the actual definition of the __init__ operation.The blank line tells the Python interpreter that the class definition is finished so that we get the >>> prompt back.
>>> Addr = Address(7,"High St","Anytown","123 456")
This creates a new instance of our Address type and Python uses the __init__ operation defined above to assign the values we provide to the internal fields. The instance is assigned to the Addr variable just like an instance of any other data type would be.
>>> print Addr.Hs_Number, Addr.Street
Now we print out the values of two of the internal fields using the dot operator to access them.
As I said we cover all of this in more detail later in the book. The key point to take away is that Python allows us to create our own data types and use them pretty much like the built in ones.
You can contact me by email at: