[Tutor] An Introduction and a question

Kent Johnson kent37 at tds.net
Fri Jun 9 22:08:25 CEST 2006


Michael Sullivan wrote:
>   Here is my code:
> 
> #!/usr/bin/env python
> 
> import random
> import time
> import math
> 
> class LinePuzzlePiece:
>    """This class defines a single playing piece for LinePuzzle"""
>    def __init__(self):
>       seed(time)
>       index = int(math.floor(uniform(1, 10)))       colorlist = ["red",
> "blue", "green" "yellow", "purple"]       self.color = colorlist[index]
> 
>    def printcolor():
>       print self.color
> 
> mypiece = LinePuzzlePiece
> mypiece.printcolor
> 
> 
> I saved the script and made it chmod +x.  However, when I run it, I get
> this:
> 
> michael at camille ~ $ ./linepuzzle.py
> michael at camille ~ $
> 
> Now, I'm no expert, but I really think something should have been
> printed, if even a blank line.  What am I doing wrong here?  Why is
> nothing printing?  Is my printcolor method even being called
> successfully?

No, you have not created a LinePuzzlePiece or called printcolor.

In Python, parentheses are required for function calls. A class or 
function name without the parentheses is a reference to the class or 
function object itself, not a call to the object. This can be very 
useful but it's not what you want!

mypiece = LinePuzzlePiece # This makes mypiece refer to the class, not 
an instace

mypiece.printcolor # This is a reference to a method of the class, but 
you don't do anything with the reference

What you really want:
mypiece = LinePuzzlePiece()
mypiece.printcolor()

Kent





More information about the Tutor mailing list