We model the world with language.
Nouns, proper nouns, verbs and adjectives.
(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!'
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?
>>> cow_names = ['Buttercup', 'Daisy', 'Bessie', 'Clover']
>>> cow_breeds = ['Friesian', 'Galloway', 'Guernsey', 'Dexter']
What could possibly go wrong with this?
>>> del cow_names[1]
>>> cow_names
>>> ['Buttercup', 'Bessie', 'Clover']
>>> del cow_breeds[2]
>>> cow_breeds
>>> ['Friesian', 'Galloway','Dexter']
(what's gone wrong here..?)
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
(This is not entirely accurate but is close enough for today)
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
>>> 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.
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