Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Question with classes 1

Status
Not open for further replies.

fmessier

Programmer
Mar 31, 2008
2
CA
I'm going through tutorial and I'm currently stuck when trying to implement classes. I get a problem with how I declare variables for a specific object. Any help would be greatly appreciated. Thanks again for taking the time to look into this.


Code:
#------
# CLASS: Cat
# Description: This creates cat objects
#------

class cat:
    def __init__(self,name,weight):
        self.name = name
        self.weight = weight
    status = 'none'
    xp = 0
 
    def DisplayName(self):
        return self.name
    
    def DisplayWeight(self):
        return self.weight
    
    def DisplayStatus(self):
        return self.status
    
    def DisplayXp(self):
        return self.xp
    
    def FeedCat(self, foodAmount):
        weight = weight + foodAmount
        
    def KillCat(self):
        status = 'Dead'
        weight = 0
    
    def TryEscape(self):
        xp = xp + 1        
    
    def Starve(self):
        weight = weight - 30
    
#----------
# loadCats
# Description: This loads the cats from the file into the array
#---------
def loadCats(loadedFile):
    catsList = []

    for line in loadedFile:
        catsList.append(line) 

    return catsList

#--------
# MAIN
#-------
def Main():

    myCat = cat('guy',100)
    myCat.DisplayName()
            
#----------
# Entry
#----------
Main()

when I run this code I get the following error:

Traceback (most recent call last):
File "C:/Python25/test.py", line 82, in <module>
Main()
File "C:/Python25/test.py", line 74, in Main
myCat.DisplayName()
File "C:/Python25/test.py", line 29, in DisplayName
return name
NameError: global name 'name' is not defined
 
traceback shows
`return name`
hence the error global name 'name' is not defined
but your code shows
`return [red]self.[/red]name`
which should be correct
 
Yes you're correct, I now know what the problem was. When I changed it to return self.name, when I would run the app it would do nothing. I just realised have I have to print the DisplayName()

Thanks for the help!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top