Learn to Code via Tutorials on Repl.it!

← Back to all posts
OOP in Python
OlauPla (160)

Object-oriented programming

Today I am going to talk about Object-oriented programming I will use OOP to reference it through out the tutorial.

This tutorial is not directly meant for python beginners. What I mean with this is: If you just started learning python as your first programming language this tutorial is not for you. Learn the basics first.

If you think something is not well explained or simply incorrect please leave it in the comments asp! I will fix it.

What do I do if I am stuck or don't understand something?

  • Think for a bit
  • Google it or ask it in the ask question of repl.it
  • If you still don't get it feel free to leave a comment

Let's get started!

What is OOP?

OOP is one of the most effective approaches to writing
software. In OOP you write classes that represent real-
world things and situations and you create instances of
those classes. For example take for a class "Human",
everyone is an instance of that class.

A class example

As I mentioned before the example of the "Human" class
we are going to code it.

import random

class Human():
   
  def __init__(self,name: str,age: int): #this is a special method
    self.name = name
    self.age = age

  def eat(self): #this is a method

    food = ['burger','spaghetti','orange','broccoli'] 
    print(f"{self.name.title()} ate a {random.choice(food)}")

  def birthday(self): #this is a method
    
    self.age += 1
    print(f"It's your birthday {self.name.title()} you are now {self.age} years old!")

  def sleep(self): #this is a method
      
      hours = [6,7,8]
      print(f"{self.name.title()} you went to sleep and slept for {random.choice(hours)} hours!")


human1 = Human("Joe", 5) #this is an instance of the class Human
print(f"Name : {human1.name}")
print(f"Age : {human1.age}")
human1.eat()
human1.birthday()
print(f"Age : {human1.age}")
human1.sleep()

This will output the following:

Name : Joe
Age : 5
Joe ate a burger
It's your birthday Joe you are now 6 years old!
Age : 6
Joe you went to sleep and slept for 7 hours!

Wow that was a big step! Let's explain everything:

First we define a class named "Human".
Then we define a special method for the class. The init method, this method will run when an instance of the "Human" class is created.
The init method takes 3 parameters self, name and age.
The self parameter is required in all method definitions and it must go first, before the other parameters. The self parameter is passed automatically to every class method. The self is a reference to the instance itself. Then we define name and age variables attached to the self. The self.name = name and self.age = age takes the values associated with each parameter and assigns it to name and then age. This might be hard to understand, and explain. Doing that makes the variables name and age available to the whole class through the self. Variables like that are called attributes.

Later we define class methods that define the things that a Human can do.

Finally we create an instance of the class human, pass in the arguments name and age. Then we print their values.
We also call the class method eat, then the birthday. We observe that the attribute age has been changed. And to end we call the sleep method.

Creating multiple instances of a class

Creating multiple instance of a class is possible, let's use the previous class as an example:

class Human():
   --snip--

human1 = Human("Joe", 5) #this is an instance of the class Human
human2 = Human("Alice", 17)

print(f"Name of human1 {human1.name}, age {human1.age}")#access the attributes
print(f"Name of human2 {human2.name}, age {human2.age}")


#call metods
human1.sleep()
human2.sleep()

Ouput:

Name of human1 Joe, age 5
Name of human2 Alice, age 17
Joe you went to sleep and slept for 8 hours!
Alice you went to sleep and slept for 6 hours!

As you can observe, multiple instances can be created.

Modifying attribute values

You can modify the age or the name of Human whenever you like. It is more easy to create methods to do that but you don't need it. Simply do this:

human1 = Human("Joe", 5) #this is an instance of the class Human
human1.age = "34"
print(human1.age)

Output:

34

Finish

I will do another tutorial on OOP if you guys like this one.

If I make another I will talk about class inheritance and default attributes

Thank you for reading my tutorial, I would like to give credit to: Eric Matthhes, his book Python Crash course helped me make this tutorial!

Comments
hotnewtop
OldWizard209 (1631)

Hey. Great tutorial but a few notes about a couple of things you wrote.

Then we define a special method for the class. The init method, this method will run when an instance of the "Human" class is created.

The __init__ method is called a dunder method, recognized by the pair of two underscores around the name.

The init method takes 3 parameters self, name, and age.

This sentence makes it seem like the __init__ method takes three parameters by default. But that's not true. The first parameter has to be the instance of the class. After that, there can be as many parameters as you want.

The self parameter is required in all method definitions and it must go first, before the other parameters. The self parameter is passed automatically to every class method. The self is a reference to the instance itself.

This is true, but the instance of the class doesn't always have to be self. It can be named anything, like potato. But the programming convention is to use self. I just made this note to avoid letting people think that self is the only thing that can be put as a first parameter. Here is an example:

class Try:
  def __init__(potato, name, age):
    potato.name = name
    potato.age = age

try_class = Try("John", 55)

print(try_class.name) # Ouput: "John"

But it is also important to note that self is the best keyword to use.

The self.name = name and self.age = age takes the values associated with each parameter and assigns it to name and then age.

Once again the keywords after self that assign the attributes can be named as any ordinary variable. They don't have to be the same as the parameter names.

class Class:
  def __init__(self, name, age):
    self.n = name
    self.a = age

try_class = Class("John", 55)

print(try_class.n) # Output: "John"

These are just a few things I had to point out. But other than that, great tutorial.

OlauPla (160)

Also I knew about the self thing but i didn't want to say it, i thought it could confuse but your right
@OldWizard209

InvisibleOne (3224)

Cool, very interesting

OlauPla (160)

Please go easy on me first tutorial