classes-objects-python-blog.png

Classes and Objects In Python

Last Updated | Jan, 13, 2021 By Kingsley Ijomah
Python is an object-oriented programming language ( OOP ), which means that we are constantly manipulating objects, in this post we are going to learn how to create a class in Python and then use that class as a blueprint to create instances also known as objects.
classes-objects-python-pinterest1.png

What is a Python class?

Python is an object-oriented programming (OOP) language, this means that almost everything in python is an object with properties and methods, therefore a class is simply what we use to construct an object, a blueprint for creating objects.

A class in python is a way of grouping data (variables) and methods (functions) that act on those data.

Create a Class

To create a class we use the class keyword followed by the Name of the class.

code
class Animal:
    "This is an animal class"
    name = "Boris"


# Output: Boris
print(Animal.name)


# Output: 'This is an animal class'
print(Animal.__doc__)

Above we created a class called Animal, and it has a name property ( variable containing a string "Boris" )

Create Object

We defined a class as a blueprint for creating objects, so what exactly are objects and how do you create one you might be asking.

Objects are copies created from a class, they contain methods ( functions ), each copy ( instance ) can be passed different data to be processed. let's have a look at an example.

code
class Animal:
    "This is an animal class"
    name = "Boris"

dog = Animal()

# Output: Boris
print(dog.name)

In the example above we created a new object and saved it into a variable called dog, to create an object we call the class name e.g Animal(), then we can call methods or properties of that class through the new object, e.g dog.name

It is also possible to feed in data to our class, this way each object process unique data and produce unique result, that is achieved through initialization as shown below:

Initialize Function

code
"""
Initialize Animal class with name and age
also includes a speak method.
"""


class Animal:
    "This is an animal class"

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def speak(self):
        print("My name is {} and I am {} years old!".format(self.name, self.age))


boris = Animal("Boris", 7)
fufu = Animal("Fufu", 4)
zorka = Animal("Zorka", 2)

boris.speak() #output: My name is Boris and I am 7 years old!
fufu.speak() #output: My name is Fufu and I am 4 years old!
zorka.speak() #output: My name is Zorka and I am 2 years old!

Above we added an initialize method to the Animal called __init__ the first parameter of methods in Python is called self, this is how objects identify themselves, we also created a speak() method, you will notice it is similar to functions we created previously, the difference is that this has self as the default parameter.

We created three objects boris, fufu and zorka, each with unique data, therefore producing unique results.

Modify Object Properties

It is possible to update class properties after they are initialized, let's have a look with an example below:

code
class Animal:
    "This is an animal class"

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def speak(self):
        print("My name is {} and I am {} years old!".format(self.name, self.age))


boris = Animal("Boris", 7)
boris.age = 12
boris.speak()  # output: My name is Boris and I am 12 years old!

Using the example above, we are able to override the age of boris by simply assigning a new value to it using the = sign.

Final Thoughts

We have covered in this post the basics of working with classes in Python, we also looked at how to create objects, add methods and properties to a class. Be sure to revise this until you feel comfortable working with classes.

Python is an object oriented programming ( OOP ) language, classes gives us a way to create our own objects to model a problem we are trying to solve, the more you learn about classes and objects, the easier you will find coding Python as a programming language.

Happy Coding!...

Please share this post with others who might benefit from it.

MY STORY

My name is Kingsley Ijomah, I am the founder of CODEHANCE, an online education platform built with you in mind, a place where I express my gratitude to a skill ( coding ) which has changed my life completely.

Learn To Code With Me.
FREE course included.

GET IN TOUCH

Enter your email address:

Delivered by FeedBurner