I have just started to learn about classes and objects in Python and I came to following problem
It doesnt seem to work with variable n in methods I defined in some cases:
for example:
def play(self):
if n < 4:
n += 1
self.mood = moods[n]
else:
self.mood = self.mood
this throws and error that n is not defined on line "if n < 4:" but if I erase this part "n += 1" error does not appear. But even after that it doesnt seem to update variable n if I use it in method:
def new_mood(self):
n = random.randint(0,2)
self.mood = moods[n]
Am I missing some fundamental knowledge here?
import random
moods = ['terrible',
'bad',
'neutral',
'good',
'great']
n = random.randint(0,2)
class animals:
def __init__(self, species, name, mood):
self.species = species
self.name = name
self.mood = mood
def default_mood(self):
self.mood = moods[2]
def new_mood(self):
n = random.randint(0,2)
self.mood = moods[n]
def play(self):
if n < 4:
n += 1
self.mood = moods[n]
else:
self.mood = self.mood
Max = animals('Dog', 'Max', moods[n])
Princess = animals('Cat', 'Princess', moods[n])
print(Max.name + ' mood is ' + Max.mood)
print(Princess.name + ' mood is ' + Princess.mood)
Max.new_mood()
Max.play()
Princess.play()
print(Max.name + ' mood is ' + Max.mood)
print(Princess.name + ' mood is ' + Princess.mood)
print(Max.mood)
print(Max.name + ' mood is ' + Max.mood)
print(Princess.name + ' mood is ' + Princess.mood)