Gentle Object Oriented Programming in Python

Nicholas H.Tollervey / @ntoll
Naomi Ceder / @NaomiCeder

We model the world with language.

Language includes:

  • Naming types of things (cats, dogs, cows)
  • Naming specific things (Garfield, Snoopy, Buttercup)
  • Describing actions (run, walk, smile, love, hate)
  • Attributing qualities (red, furry, hot, scary)


Nouns, proper nouns, verbs and adjectives.

Computers need to model the world too!

Like this:

(Python Refresher)


    def moo(name, message='MOO!'):
        """
        A function to return a greeting.
        """
        return '{} says, {}'.format(name, message)
                    

A function takes arguments and returns a result, like this:


    >>> moo('Buttercup')
    'Buttercup says, MOO!'
    >>> moo('Daisy', 'MooOOOOooooo!')
    'Daisy says, MooOOOOooooo!'
                    

Growing the Herd...

If we have 4 cows...


    >>> a_cow = 'Buttercup'
    >>> another_cow = 'Daisy'
    >>> yet_another_cow = 'Bessie'
    >>> yet_another_other_cow = 'Clover'
    >>> a_cow_breed = 'Friesian'
    >>> another_cow_breed = 'Galloway'
    >>> yet_another_cow_breed = 'Guernsey'
    >>> yet_another_other_cow_breed = 'Dexter'
                    

But what if we have 50 cows? 500?

lists help...


    >>> cow_names = ['Buttercup', 'Daisy', 'Bessie', 'Clover']
    >>> cow_breeds = ['Friesian', 'Galloway', 'Guernsey', 'Dexter']
                    

What could possibly go wrong with this?

Well, this...


    >>> del cow_names[1]
    >>> cow_names
    >>>  ['Buttercup', 'Bessie', 'Clover']
    >>> del cow_breeds[2]
    >>> cow_breeds
    >>> ['Friesian', 'Galloway','Dexter']
                    

Uh-oh...

(what's gone wrong here..?)

Basic OOP
Concepts

A class defines a type of thing

An object is an instance of a class

A method specifies a behaviour of an object

An attribute defines the quality of an object

Crib sheet

  • Class = Noun
  • Object = Proper noun
  • Method = Verb
  • Attribute = Adjective

(This is not entirely accurate but is close enough for today)

What about Python?

Python Classes


    class Cow:
        """
        A pythonic cow. :-)
        """

        def __init__(self, name='Cow', breed=None):
            """
            Called when the class is instantiated.
            """
            self.name = name
            self.breed = breed

        def moo(self, message='MOO!'):
            """
            A bovine greeting method (see earlier slide).
            """
            return '{} says, {}'.format(self.name, message)
                    

Created in the file cow.py

A Herd of Pythonic Cows


    >>> from cow import Cow
    >>> a_cow = Cow('Buttercup', 'Friesian')
    >>> a_cow.name
    'Buttercup'
    >>> a_cow.breed
    'Friesian'
    >>> a_cow.moo()
    'Buttercup says, MOO!'
    >>> another_cow = Cow('Daisy', 'Galloway')
    >>> another_cow.name
    'Daisy'
    >>> another_cow.breed
    'Galloway'
    >>> another_cow.moo('MooOOOOooooo!')
    'Daisy says, MooOOOOooooo!'
                    

a_cow and another_cow are instances of the Cow class.

Parrots!

Your task...

  • Create a "Parrot" class.
  • You must be able to give a parrot a name and catch-phrase (e.g. "Pieces of eight...").
  • Instantiate a Parrot with the name "Polly" and a catch-phrase of your choosing.
  • Call Polly's "speak" method so Polly returns her catch-phrase.
  • Bonus points for creativity and surprises!

Crib sheet...


    class Cow:
        """
        A pythonic cow. :-)
        """

        def __init__(self, name='Cow', breed=None):
            """
            Called when the class is instantiated.
            """
            self.name = name
            self.breed = breed

        def moo(self, message='MOO!'):
            """
            A bovine greeting method (see earlier slide).
            """
            return '{} says, {}'.format(self.name, message)

    my_cow = Cow('Buttercup', 'Galloway')
    print(my_cow.moo())
                    

Saved in the file cow.py and run with the command: python cow.py

Show and Tell