Reputation: 67
I have two class which is Animal and Zoo. Animal for store the data of the type and its sex
class Animal:
def __init__(self, types, sex):
self.types=types
self.sex = sex
Zoo class is for storing all objects from the Animal class.
class Zoo:
def __init__(self):
self.zoo =[]
def enters (animal):
self.zoo.append(animal)
def removes (self, types, sex):
self.types = types
self.sex=sex
for i in range(0,len(self.zoo)):
if self.name.lower() and self.sex.lower() in self.zoo[i]:
del self.zoo[i]
break
else:
print("The animal is not exist")
break
I want to do the removal of the animal using their type and sex.
p=Zoo()
dog = Animal("Poodle","male")
cat = Animal("Persian","female")
p.enters(dog)
p.enters(cat)
p.removes("Poodle","male")
I got an error that said the object Animal is not iterable. Did anyone know what I have been missing? I thought I already store zoo in the list.
Upvotes: 0
Views: 72
Reputation: 5980
The problem is this line:
if self.name.lower() and self.sex.lower() in self.zoo[i]:
Firstly, the conition will always be True
(because self.name.lower()
will always return a non-empty string except if self.name
is empty, and non-empty strings evaluate to True). Next, you are trying to iterate over your Animal
class (x in y
iterates over y and checks if any of the elements of y == x). That's why you get that not iterable error. Finally, self.name
is nowhere defined, so I wonder how you get to that error at all. Code should be like this:
class Animal:
def __init__(self, name, sex):
self.name = name
self.sex = sex
class Zoo:
def __init__(self):
self.zoo =[]
def add_animal(animal):
self.zoo.append(animal)
def remove_animal(self, name, sex):
for n, animal in enumerate(self.zoo): # produces a list like [(0, Animal("Poodle","male")), (1, Animal("Penguin","male"))]
if name == animal.name and sex == animal.sex:
del self.zoo[i]
break
else: # This gets only excuted when the break above was NOT executed
print("Animal %s with sex %s does not exist" % (name, sex))
p = Zoo()
dog = Animal("Poodle", "male")
cat = Animal("Persian", "female")
p.add_animal(dog)
p.add_animal(cat)
p.remove_animal("Poodle","male")
Upvotes: 1