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

FOR LOOP , RANGE

  FOR LOOP  A  while  loop is perfect to use when we  don't  know how many times we want the loop to repeat.  If we have an idea of how many times we want the loop to repeat, we can use a  for  loop to loop code in exactly the same way the  while  loop did.  EXAMPLE :  for counter in range(10):   print(counter) RANGE  The  range  function creates a list of numbers in the range you create. If you only give it one number, it will start at  0  and move to a state where the final number is  one less  than the number in the brackets. In this case, the final number would be  9 .  EXAMPLE :  total = 0 for number in range(100) :   total += number   print(total)

OS LIBRARY , TIME LIBRARY

  What is the os library? It allows us to "talk" to the console. One of the most powerful things we can do with this library is allow it to clear the console EXAMPLE: import os print("Welcome") print("to") print("Replit") os.system("clear") username = input("Username: ")  Time Library We can import a second library by placing a  ,  after the name of the first library. EXAMPLE: import os, time print("Welcome") print("to") print("Replit") time.sleep(10) os.system("clear") username = input("Username: ")  NOTE:  from replit import audio import os, time def play():   source = audio.play_file('audio.wav')   source.paused = False # unpause the playback   while True:     stop_playback = int(input("Press 2 anytime to stop playback and go back to the menu : ")) # giving the user the option to stop playback     if stop_playback == 2:       source.paused = True # let'...

ALL ABOUT WHILE LOOP

 WHILE LOOP  A  while  loop allows your code to repeat itself based on a condition you set.   EXAMPLE : counter = 0 while counter < 10:   print(counter)   counter +=1 Infinite Loop  You have to be  really  careful that you don't accidentally invoke an infinite loop! This is where the computer will loop code until the end of time. Without a break. Forever.  This is just saying "count to 10 by 1 each time." to make the loop end. Don't forget, if your  condition  is a  >  then you might need to  -= . This will subtract from the variable instead of adding to it.   EXAMPLE : counter = 0 while counter < 10:   print(counter)    counter += 1