What is a class and an object in python programming?

Learn what is a class and an object in python programming. Key concepts of object oriented programming paradigm. Start writing code as a profesional.

Card image cap

Hey there! In this article you will learn what is a class and an object in python programming. The two key concepts of object oriented programming. You will learn what is a class in python and why it is important if you are serious about learning programming. Also you will learn how to create a class in python.

Object Oriented Programming in Python https://img.youtube.com/vi/7oBwoyrSS7E/default.jpg Learning the basics of object oriented programming for absolute beginners 2020-07-22 https://youtu.be/7oBwoyrSS7E

Classes and objects

Let’s start with the key concepts. What is a class in python programming?  and what is an object? Everyone knows what object means. Any tangible thing that you can sense, feel and manipulate is an object. In software, formally speaking, a class is a collection of data and associated behaviours. This will make sense in a minute.

Here is a python class example: a person can be represented as a class. Then I will define what information is relevant to represent a person, for instance, the name and age. Name and age will be our data. Then I will define the behaviours for that class, also known as python classes methods. I will define two behaviours for this class: ‘say hello’ and ‘say name’ . Perfect! We just defined a class. In other words, we just defined a template with what the object will contain. When you assign values to that template ,then you are creating an object.

Class examples

Let’s see an example. A person with name and age is the class. Then you can create one object and save it in a variable called ‘Person1′ with name=’Peter’ and age=16. Another Person object with name=’Mary’ and age=32. You could have another class Circle and its data will be the radius and colour, and its behaviour is calculating the area. Then I will have an object of the class circle with value radius=3 and colour=yellow and another object of the class Circle with radius=5 and colour=blue.  

What’s object oriented programming?

Let’s talk about object oriented programming. Object Oriented means that you solve a problem or a task representing the entities of your problem as classes.

For instance if your problem is calculating the area of a circle, you will need the radius and then you will do 2*PI*radius.

You could solve this problem with a non object oriented approach: creating a method that calculate the area passing the radius as a parameter. Or if you use the object oriented approach, you will define a class Circle with a field radius and a method that calculate the area.

What are the benefits of using object oriented approach? It helps reducing the complexity and increase maintainability. Classes help you organise your code, keeping together code that is related in some logical way.

Object Oriented Programming with python

How can you translate all this into python? In other words, how to create a python class, then objects based on a class and use those objects. To follow the previous example, I will create a class person with two fields, name and age and the class methods ‘say_hello’ and ‘say_name’.

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age
  
  def say_hello(self):
    print('Hello')
  
  def say_name(self):
    print('My name is ' + self.name)

person1 = Person('Peter', 28)
person2 = person('Mary', 32)
person1.say_hello()
person2.say_name()

The __init__ method is the constructor. When you call this method, you are creating an object of the class Person. The main task of the constructor is populating your object with values. The results from the code above are the following:

Hello
My name is Mary

We have seen how to create a class and how to use it, let’s talk out attributes

Global attributes and instance attributes

We seen attributes is the relevant data that we will like to save about our object, eg. for a person we might save name and age. These are instance attributes because they are initialised in the constructor, the __init__ method. This attributes can only be accessed through an object of the class, also known as instance. However there is another type of attribute, the global attributes. Global attributes can be accessed through the class, you don’t need to create an instance to use them. Let’s see an example

class Person:
    
    race = 'Human Being' # global attribute
    
    def __init__(self,name,age):
        self.name = name  # instance attribute
        self.age = age # instance attribute
        
    def say_hello(self):
        print("Hello, my name is" + self.name)
        
    def say_age(self):
        print("I am " + self.age +" years old")

# This will return the following error
# AttributeError: type object 'Person' has no attribute 'name'
print(Person.name)

person_instance = Person('Mary',30)

# This will work. name is an instance attribute, therefore I need
# to create an instance of my class to use it
print(person_instance.name)

# This will work. Race is a global attribute so I can access it through
# the class, I don't need an instance.
print(Person.race)   # Return Human Being

# Global instance can be accessed via the class or via the instance.
print(person_instance.race)

Global attributes can be accessed through the class or through the instance and instance attributes only through the instance.

Time to practice!

Here is a little exercise so you can check your understanding. Try to solve it yourself before checking the solution! 🙂

Exercise: Create class Circle that has one global attribute with the value of PI and an instance attribute radius. And create an area method to calculate the area of the circle.

Solution

class Circle:
    PI =3.14

    def __init__(self,radius):
        self.radius = radius

    def area(self):
        return self.PI * self.radius ** 2

circle_instance = Circle(10)
print(circle_instance.area())

Conclusion

In conclusion, we covered what is a class and an object in programming. Remember class is the template, the object is created from the class and it holds the actual values. End of the article where I covered what python classes and objects are, what object oriented programming is and why is important. And we have seen how to use python classes and objects.

In case you would like to learn more about python, I highly recommend the following book. It will help you to get on professional Python development straight away, no additives, it is worth every single word.

What’s next?

Thank you so much for reading this article!! If you like the article and you would like to be notified when I publish more articles about how to become a software developer and how to improve your skills, feel free to subscribe.

Learn Ethical Hacking From Scratch Course

Become an ethical hacker that can hack computer systems like black hat hackers and secure them like security experts.

Project-Based Programming Introduction

Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications

100% Recommended book for Java Beginners

Unique lay-out and teaching programming style helping new concepts stick in your memory

90 Specific Ways to Write Better Python

Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples

Grow Your Java skills as a developer

Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.

Write Code as a Professional Developer

Excellent read for anyone who already know how to program and want to learn Best Practices

Every Developer should read this

Perfect book for anyone transitioning into the mid/mid-senior developer level

Great preparation for interviews

Great book and probably the best way to practice for interview. Some really good information on how to perform an interview. Code Example in Java