Bookkeeping Functions in Classes

Object Initialization (Constructors)  

When we create an instance of a class, we often want to initialize its data members (fields).
 
We could create an instance of time set to12:30:30 with the following code in main:
 
    # main
    t = Time()
    t.hour=12
    t.minute=30
    t.second=30
 
This is quite laborious. A constructor is a special method for initializing fields on creation.
 
In Python, a constructor is a method with the special name __init__  (two underscores around "init")
 
Using a constructor, the code in the sample main can be reduced to one line.
 
Here's a modified class Time and modified main program that creates a Time instance:
 
    class Time:
 
        def __init__(self, hours=0, minutes=0, seconds=0):
 
            self.hours = hours
            self.minutes = minutes
            self.seconds = seconds
 
       # main
        t = Time(12, 30, 30)

Note that the parameters have default values given to them. This allows a programmer to also create a Time class without specifying the hour, minute, and second on the creation:

        t2 = Time()

Object Equality

Consider the following main program:
 

            t1 = Time(4,5,22)
            t2= Time(4,5,22)
            if (t1==t2)
                print "t1 is same as t2"
 
Will anything be printed?
 
With objects, "==" is defined to compare the addresses of the two objects.

Python allows a programmer to redefine == for a class by using the special name __eq__.
 
    class Time:
        def __init__(self, hours=0, minutes=0, seconds=0):
            self.hours = hours
            self.minutes = minutes
            self.seconds = seconds

        def __eq__(self, other):
           
if ((self.hours==other.hours) and
            (self.minutes==other.minutes) and
            (self.seconds=other.seconds)):
                return True
            else
                return False;
 
Given this __eq__, we'll get a different result for:
 
   
if __name__ == '__main__':
            t1 = Time(4,5,22)
            t2= Time(4,5,22)
            if (t1==t2)
                print "t1 is same as t2"


When Python sees == on two objects, it checks if the class of the objects has an __eq__. If not, it calls the default comparison (compare addresses).

String Representation

When we call print on an object, Python does not print the contents of the object, it prints its address.
 
A programmer can write a method with the name __str__ to provide a string representation for an object (which can be printed)
 
 class Time:
     # ...
 
    def __str__(self): 
        return str (self.hours) +":"+ str(self.minutes) + ":" +str(self.seconds)

With __str__ defined, when one prints a time object, it will display the data.

In-Class Problem

Modify your Coordinate code so that it has a proper constructor, equality method, and string representation. Write a main method that tests all of these functions.

Recent site activity