Classes are excellent in this case. That's what they are there for - organizing data :)
Consider using a base class for Animal, and subclass the other animal if you know the value at compiletime. Or use a subklass where you fill inn the attributes at load-time. I included some examples of how it can be done. This is python 3 syntax, so bear with me :)
class Animal(object):
"""
Base class for all animals
"""
def __init__(self, **kwargs):
for attribute, value in kwargs.items():
setattr(self, attribute, value)
def compare(self, attribute, otherAnimal):
try :
myValue = getattr(self, attribute) # if attribute = tail, this equals myValue = self.tail
otherValue = getattr(otherAnimal, attribute) # -- = -- this equals otherValue = otherAnimal.tail
highObject = self if myValue > otherValue else otherAnimal # Find the object with the highest value
lowObject = self if myValue < otherValue else otherAnimal # Find the object with the lowest value
if myValue == otherValue: # Values might me equal
print("{0} and {1} has the same amount of {2}".format(self.getName(), otherAnimal.getName(), attribute))
else: # Values are not equal
print("{0} has more {1} than {2}".format(highObject.getName(), attribute, lowObject.getName()))
except AttributeError as e: # This exception is raies if the attribute doesn't exist
print(e)
def equalities(self, otherAnimal):
return [x for x in self.__dict__ if not x.startswith('__')
and hasattr(otherAnimal, x)
and getattr(self, x) == getattr(otherAnimal, x)]
def getName(self):
return self.__class__.__name__ # Default name to class-name
class Cow(Animal):
def __init__(self):
self.legs = 4
self.eyes = 2
self.tail = 1
class Spider(Animal): …