Skip to main content

OOP , Classes , Instantiation ,More Methods

 OOP
Object Oriented Programming (OOP) is a programming paradigm (a way of thinking about how to solve a problem) that is based on classes and objects, which store all of their data and behaviors inside them.
You can think of a class like a cookie cutter, or template. It has pre-defined characteristics (shape, size etc).
Objects are like the cookies created using the cutter. They all get the same size and shape, but then we can personalize each one (sprinkles, icing, etc).
Some programming languages, like Java, are entirely based on OOP. So all you Java coders will be used to this way of thinking.

Classes 

👉 Let's create a template, known as a class. Our theme is animals. Our class will contain all the characteristics (think variables) that animals have in common.
Remember that this is just a template. All the characteristics are set to 'None' in the template and we will customize these values when we use the template to create (instantiate) each animal. The values will be passed as arguments into the __init__ subroutine inside each animal object.
We also want to create a subroutine called init (short for initialisation) which tells the class what to do when it is used to create each instance of an animal.
If you're a Python programmer, then this may take some getting used to, but stay with it.
This approach lets us create a template for something like an enemy in a video game, and then use that template to create, say, 20 enemies. Instead of having to code each one individually.
It's very powerful for large scale projects, but we're going to start small. 
class animal:
  species = None
  name = None
  sound = None
  # Sets the characteristics

  def __init__(self, name, species, sound):
    self.name = name
    self.species = species
    self.sound = sound
  # 'self' means 'this object'
  # This code sets the name, species and sound of each object to the arguments passed in when it is created (instantiated). 

Instantiation

Instantiation means 'use the template to create an object'. Like pressing the cutter into the dough to make a cookie.

👉 Let's instantiate a dog object. 

class animal:
  species = None
  name = None
  sound = None
  # Sets the characteristics

  def __init__(self, name, species, sound):
    self.name = name
    self.species = species
    self.sound = sound

##### THE NEW BIT #######

dog = animal("Brian", "Canine", "Woof") # Use the animal class to create a new object called 'dog' with the following parameters. 

👉 Now let's output the dog's name.


More Methods

Subroutines inside an object are called methods.

👉 Let's create a talk method inside the animal class. This can then be used by both our dog and cow objects. 

class animal:
  species = None
  name = None
  sound = None
  # Sets the characteristics

  def __init__(self, name, species, sound):
    self.name = name
    self.species = species
    self.sound = sound

dog = animal("Brian", "Canine", "Woof")
print(dog.name)

##### THE NEW BIT ################
cow = animal("Ermintrude", "Bo Taurus", "Moo")
print(cow.sound) 
class animal:
  species = None
  name = None
  sound = None
  # Sets the characteristics

  def __init__(self, name, species, sound):
    self.name = name
    self.species = species
    self.sound = sound

  def talk(self):
    print((f"{self.name} says {self.sound}"))  

👉 Now I can use the talk() method for each object.

class animal:
  species = None
  name = None
  sound = None
  # Sets the characteristics
  def __init__(self, name, species, sound):
    self.name = name
    self.species = species
    self.sound = sound
  def talk(self):
    print((f"{self.name} says {self.sound}")) 
  # 'self' means 'use the identifier given to the object that is accessing this method'.
 So If I use it with dog it will become 'dog.talk()' etc.
dog = animal("Brian", "Canine", "Woof")
dog.talk()
cow = animal("Ermintrude", "Bo Taurus", "Moo")
cow.talk() 
Inheritance
Inheritance means that we can take the template from animal and break it down into sub-classes that use all the attributes and methods from that class, but also add their own attributes.

This is useful when we're thinking about animals as we can start breaking the animal kingdom apart by species.

When I create the sub-class, I use the name of its parent class as a parameter. This means 'get all the features of animal and use them here too'.

Here, I'm creating a sub-class of bird, which inherits from animal.

👉 I can then create the 'bird specific' features inside the bird sub-class.

class animal:
  species = None
  name = None
  sound = None
  # Sets the characteristics
  def __init__(self, name, species, sound):
    self.name = name
    self.species = species
    self.sound = sound
##### The New Bit ##########
class bird(animal):
  def __init__(self):
    self.name = "Bird"
    self.species = "Avian"
    self.sound = "Tweet"
    # This automatically sets the information for each bird when it is created.
polly = bird() # Instantiates a new bird which gets it's details from the sub-class.
polly.talk() # polly uses the `talk()` method from the animal class


👉 Let's add a specific color to the bird class.

class bird(animal):
  def __init__(self):
    self.name = "Bird"
    self.species = "Avian"
    self.sound = "Tweet"
    self.color = color # Only applies to the bird sub class
polly = bird("Green") # Sets polly's colour to 'Green'
polly.talk()
print(polly.color) # Prints polly's color


 



x

Comments

Popular posts from this blog

Web Scraping

 Web Scraping Some websites don't have lovely APIs for us to interface with. If we want data from these pages, we have to use a tecnique called scraping. This means downloading the whole webpage and poking at it until we can find the information we want. You're going to use scraping to get the top ten restaurants near you. Get started 👉 Go to a website like Yelp and search for the top 10 reastaurants in your location. Copy the URL.   url = "https://www.yelp.co.uk/search?find_desc=Restaurants&find_loc=San+Francisco%2C+CA%2C+United+States"   Import libraries 👉 Import your libraries. Beautiful soup is a specialist library for extracting the contents of HTML and helping us parse them. Run the Repl once your imports are sorted because we want the Beautiful Soup library to be installed (it'll run quicker this way). import requests from bs4 import BeautifulSoup url = "https://www.yelp.co.uk/search?find_desc=Restaurants&find_loc=San+Francisco%2C+CA%2C+Unite...

Client/Server Logins

 Client/Server Logins Waaay back when we learned about repl.db, we mentioned the idea of a client/server model for storing data in one place and dishing it out to multiple users. This model is the way we overcome the issue with repl.db of each user getting their own copy of the database. Well, now we can use Flask as a webserver. We can build this client server model to persistently store data in the repl (the server) and have it be accessed by multiple users who access the website via the URL (the clients). Get Started Previously, we have built login systems using Flask & HTML. We're going to start with one of those systems and adapt it to use a dictionary instead. 👉 First, let's remind ourselves of the way the system works. Here's the Flask code. Read the comments for explanations of what it does: from flask import Flask, request, redirect # imports request and redirect as well as flask app = Flask(__name__, static_url_path='/static') # path to the static fil...

HTTP & Sessions

 HTTP & Sessions One of the main protocols (rules that govern how computers communicate) on the web is called HTTP. HTTP is what is known as a stateless protocol. This means that it doesn't 'remember' things. It's a bit like having a conversation with a goldfish. You can ask a question and get a reply, but when you ask a follow up question, the original has already been forgotten, as has who you are and what you were talking about. So if HTTP is stateless, how come my news site remembers to give me the weather for my home town, my preferred South American river based online store tells me when it's time to order more multivitamins, and I'm justifiably proud of my #100days success streak? The answer is......... Sessions Sessions are a way of storing files on your computer that allows a website to keep a record of previous 'conversations' and 'questions' you've asked. By using sessions, we can store this info about the user to access later....