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

Automate! Automate!

 Making this customizable 👉So how about making our search user customizable? In the code below, I have: Asked the user to input an artist (line 14) Tidied up their input (line 15) formatted the search URL as an fString that includes the artist (line 19) Here's tAutomate! Automate! We are so close. I can taste it, folks! Massive kudos on getting this far! Today's lesson, however, will work best if you have one of Replit's paid for features (hacker plan or cycles). Free plan Repls 'fall asleep' after a while. Automation kinda relies on the Repl being always on. If you have hacker plan or you've bought some cycles, then you can enable always on in the drop down menu that appears when you click your Repl name (top left).he code: This is important because when our repl is always running, it can keep track of time and schedule events. 👉 I've set up a simple schedule that prints out a clock emoji every couple of seconds. It works like this: Import schedule librar...

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....

Incoming!

 Incoming! Today, we're going to learn how to deal with data from forms in Flask. 👉 To start, I've added yesterday's HTML code for my form in main.py for you already. (You're welcome!) Go take a look! 👉 However, at the moment, the app.route() has no method associated with it, so I need to create a route for this page to receive the data. First, I need a new import: request. Then I create the app.route - I also need to add an extra argument to specify the methods being received. At the moment, that's just 'post', but it does need to be ALL CAPS - POST. Finally I define the process() subroutine that returns request.form 👉 Here's the new code on its own: from Flask import Flask, request app.route('/process', methods=["POST"]) def process():   return request.form 👉 And here it is as part of the whole code: from flask import Flask, request app = Flask(__name__) app.route("/process", methods=["POST"]) def process():   ...