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 🍕…
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
Follows the pattern: class <name>(<parent class>)
.
You can find many examples in: /opt/conda/envs/sds2020/lib/python3.7/site-packages
(Docker).
def __init__(self, sauce:str='tomato', cheese:str='mozzarella'):
self.toppings = []
self.sauce = sauce
self.cheese = cheese
Follows the pattern: def __init__(self, <params>)
Follows the pattern: def <function>(self, <params>):
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']
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']
A class is defined by:
A class is initialised by:
All methods have to have this:
This is an instance variable:
This is a class variable (in the class definition):
So the keyword
self
refers to the instantiated object: the object always passes a reference to itself as the first parameter in any method.
Classes • Jon Reades