Classes

Jon Reades

A tight coupling of the data, and the functions that act on the data.

What’s an Object?

Objects are instantiated versions of classes:

  • "hello world" is an instance of a string, and
  • ['A','B',1,3] is an instance of a list.

The class is your recipe, the object is your 🍕…

Really… Like a Pizza!

class pizza(object):
  base = 'sourdough'
  
  def __init__(self, sauce:str='tomato', cheese:str='mozzarella'):
    self.toppings = []
    self.sauce = sauce
    self.cheese = cheese
    
  def add_topping(self, topping:str) -> None:
    self.toppings.insert(len(self.toppings), topping)
  
  def get_pizza(self) -> list:
    ingredients = [self.base, self.sauce, self.cheese]
    ingredients.extend(self.toppings)
    return ingredients

Class Definition

class pizza(object):

    base = 'sourdough'
    ...

Follows the pattern: class <name>(<parent class>).

You can find many examples in: /opt/conda/envs/sds2020/lib/python3.7/site-packages (Docker).

The Constructor

  def __init__(self, sauce:str='tomato', cheese:str='mozzarella'):
    self.toppings = []
    self.sauce    = sauce
    self.cheese   = cheese

Follows the pattern: def __init__(self, <params>)

Adding Toppings

def add_topping(self, topping:str) -> None:
    self.toppings.insert(len(self.toppings), topping)

Follows the pattern: def <function>(self, <params>):

Getting the Pizza

def get_pizza(self) -> list:
    ingredients = [self.base, self.sauce, self.cheese]
    ingredients.extend(self.toppings)
    return ingredients

Pizza in Action

p = pizza(sauce='white')
p.add_topping('peppers')
p.add_topping('chillis')
p.get_pizza()
> ['sourdough', 'white', 'mozzarella', 'peppers', 'chillis']

Check it Out

p1 = pizza(sauce='white')
p1.add_topping('peppers')
p1.add_topping('chilis')

p2 = pizza()
p2.base = "Plain old base"
p2.add_topping('pineapple')
p2.add_topping('ham')

p1.get_pizza()
> ['sourdough', 'white', 'mozzarella', 'peppers', 'chilis']
p2.get_pizza()
> ['Plain old base', 'tomato', 'mozzarella', 'pineapple', 'ham']

But…

pizza.base='Crusty' # Like changing a package var!
p1.get_pizza()      # Base has changed
# ['Crusty', 'white', 'mozzarella', 'peppers', 'chilis']
p2.get_pizza()      # Base has not changed!
# ['Plain old base', 'tomato', 'mozzarella', 'pineapple', 'ham']

p3 = pizza()
p3.get_pizza()      # Base has changed
# ['Crusty', 'tomato', 'mozzarella']

Recap: How to Make a Pizza

A class is defined by:

class <name>(<parent class):
  ...

A class is initialised by:

  def __init__(self, <any_parameters>):
    ...

All methods have to have this:

  def <method>(self, <any_parameters>):
    ...

Recap: How to Make a Pizza (cont’d)

This is an instance variable:

  self.<var> = <something>

This is a class variable (in the class definition):

  <var> = <something>

Respect Your Self

So the keyword self refers to the instantiated object: the object always passes a reference to itself as the first parameter in any method.

Resources