fork download
  1. ''' class_Animal_1.py
  2. a look at a simple Python class
  3.  
  4. a class combines methods/functions that belong together
  5. to keep methods private, prefix with a double underline
  6.  
  7. '''
  8.  
  9. class Animal():
  10. """
  11. class names by convention are capitalized
  12. """
  13. def __init__(self, animal, sound):
  14. """
  15. __init__() is the 'constructor' of the class instance
  16. when you create an instance of Animal you have to supply
  17. it with the name and the sound of the animal
  18. 'self' refers to the instance
  19. if the instance is dog, then
  20. name and sound will be that of the dog
  21. 'self' also makes name and sound available
  22. to all the methods within the class
  23. """
  24. self.name = animal
  25. self.sound = sound
  26.  
  27. def speak(self):
  28. """
  29. the first argument of a class method is always self
  30. this method needs to be called with self.speak() within
  31. the class, or the instance_name.speak() outside the class
  32. """
  33. print( "The %s goes %s" % (self.name, self.sound) )
  34.  
  35.  
  36. # create a few class instances
  37. # remember to supply the name and the sound for each animal
  38. dog = Animal("dog", "woof")
  39. cat = Animal("cat", "meeouw")
  40. cow = Animal("cow", "mooh")
  41.  
  42. # now you can call each animal's function/method speak()
  43. # by simply connecting instance_name and speak() with a '.'
  44. cow.speak()
  45. cat.speak()
  46. dog.speak()
  47.  
  48. # you can also access variables associated with the instance
  49. # since cow is the instance
  50. # self.sound becomes cow.sound
  51. print(cow.sound)
  52.  
Success #stdin #stdout 0.09s 10832KB
stdin
Standard input is empty
stdout
The cow goes mooh
The cat goes meeouw
The dog goes woof
mooh