''' class_Animal_1.py
a look at a simple Python class
a class combines methods/functions that belong together
to keep methods private, prefix with a double underline
'''
class Animal():
"""
class names by convention are capitalized
"""
def __init__(self, animal, sound):
"""
__init__() is the 'constructor' of the class instance
when you create an instance of Animal you have to supply
it with the name and the sound of the animal
'self' refers to the instance
if the instance is dog, then
name and sound will be that of the dog
'self' also makes name and sound available
to all the methods within the class
"""
self.name = animal
self.sound = sound
def speak(self):
"""
the first argument of a class method is always self
this method needs to be called with self.speak() within
the class, or the instance_name.speak() outside the class
"""
print( "The %s goes %s" % (self.name, self.sound) )
# create a few class instances
# remember to supply the name and the sound for each animal
dog = Animal("dog", "woof")
cat = Animal("cat", "meeouw")
cow = Animal("cow", "mooh")
# now you can call each animal's function/method speak()
# by simply connecting instance_name and speak() with a '.'
cow.speak()
cat.speak()
dog.speak()
# you can also access variables associated with the instance
# since cow is the instance
# self.sound becomes cow.sound
print(cow.sound)