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)

CONTINUE COMMAND AND EXIT LINE

  The Continue Command  The  continue  command stops executing code in the loop and starts at the top of the loop again. Essentially, we want to kick the user back to the original question. EXAMPLE : while True:   print("You are in a corridor, do you go left or right?")   direction = input("> ")   if direction == "left":     print("You have fallen to your death")     break   elif direction == "right":     continue   else:     print("Ahh! You're a genius, you've won") NOTE :  The  else  statement refers to any input besides left or right (up or esc). Since the user is a winner, we do  not  want to use  break  or it would say they have failed.  EXIT  COMMAND LINE  The previous code continues to loop even after the user has won. Let's fix that with the  exit()  command EXAMPLE: print("Let's play chutes and ladders. Pick ladder or chute.") while...

IF AND ELSE STATEMENT

  If Statements    These statements are a bit like asking a question. You are telling the computer:  if  something is true,  then  do this specific block of code. Double equals ( == ) is asking the computer to compare if these two things are  exactly  the same.  EXAMPLE :  myName = input("What's your name?: ") if myName == "David":  What is else? IF  the condition is  not  met with the  if  statement, then we want the computer to do the  else  part instead. Likewise, if the condition  is  met in the  if  statement, then the  else  bit is ignored by the computer. The  else  statement must be the first thing  unindented  after the  if  statement and in line with it    EXAMPLE :  myName = input("What's your name?: ") if myName == "David":  print("Welcome Dude!")  print("You're just the baldest dude I've ever seen...