Creating and Using Objects

Once we have a class definition, we can make objects which are instances of that class. We do this by evaluating the class as if it were a function: classname (). When we make one of these class calls (for example, Die()), two things will happpen.

  • A new object is created. This object has a reference to its class definition.
  • The object's initializer method, __init__, is called. We'll look at how you define this method function in th next section.

Let's create two instances of our Die class.

>>> 

d1= Die()

>>> 

d2= Die()

>>> 

print d1.roll(), d2.roll()

1 4
>>> 

print d1.value, d2.value

1 4
>>> 

print d1, d2

<__main__.Die instance at 0x30427c> <__main__.Die instance at 0x30477c>
>>> 
d1.roll()

3
>>> 
d2.roll()

6

We use the Die class object to create two variables, d1, and d2; both are new objects, instances of Die.

We evaluate the roll method of d1; we also evaluate the roll method of d2. Each of these calls sets the object's value variable to a unique, random number. There's a pretty good chance (1 in 6) that both values might happen to be the same. If they are, simply call d1.roll and d2.roll again to get new values.

We print the value variable of each object. The results aren't too surprising, since the value attribute was set by the roll method. This attribute will be changed the next time we call the roll method.

We also ask for a representation of each object. If we provide a method named __str__ in our class, that method is used; otherwise Python shows the memory address associated with the object. All we can see is that the numbers are different, indicating that these instances are distinct objects.