DEV Community

Cover image for PYTHON CLASSES: A BEGINNER’S GUIDE
Emmanuel Munyite
Emmanuel Munyite

Posted on

PYTHON CLASSES: A BEGINNER’S GUIDE

Classes, yea I know. Not a friendly area when it comes to newbie programmers, and honestly, it was also a nightmare for me when I was getting started with python. But with time, and as you ask any programmer who has been in the game long enough, you’ll come to see that indeed classes are one of the best features In python programming. The concept behind classes is that we can model real life things/objects in our programs and from those classes, we can create as many instances as possible. I this article, we are going to have a simple introduction to the concept of classes in python, and how you can begin using them in your programs in a fun and easy way.

Classes: What are they?

So classes, what are they? Well, in simple terms you can think of classes as being representations of real world entities. By real world entities I mean things like cars, buildings, people, mobile phones, computers etc, basically anything we see today. So a class is just a collection of features, behaviors and actions that the real world entity we are trying to represent has. For example, take a person, what are some of the characteristics that a person might have. Well we know that a person can have a name, an age, a height/weight, this are just the basic characteristics that a person might have. What about behaviors/actions that a person can perform, well we know that a person can walk, talk, eat, run to say the least. We can represent all this characteristics,features and behaviors of a person simply by creating a person class. In our example above, the characteristics/features of the person, Eg the name, the age, are what we call attributes. In programming terms, an attribute, is just something that describes an object, I.e tells us more about an object. And for the behaviors/actions that a person can perform Eg run, walk etc, those are called methods. A method, is a function, that we’ll create in our classes, to represent the action that an object can perform. Once we have created the person class, then we can create instances of that class. For example in our person class, an instance would now be like your brother, or a friend, or just anyone. They are all people, so we can model them using the person class. We can simply think of a person class as being a set of instructions or a recipe of making a person/instance, in which case, the instance would now be your brother.

How to define classes

To create classes in your python programs, we’ll start with the class keyword, followed by the name of the class, then full colon. It is always good to give the class a descriptive name, that describes what it is that you are trying to model and the name of the class should begin with a capital letter. For example, to declare the person class we’ll start with:

class Person:
Enter fullscreen mode Exit fullscreen mode

Once we have declared the class, we need to initialize it. We can do so by creating the init() method, which will contain the attributes that the class will have. Also note, that everything belonging to the class, after the class declaration, should be indented.
For our example, let’s create the person class and initialize it with two attributes, a person name and an age

Class Person:
    def __init__(self,name,age):
        self.name = name
        self.age = age
Enter fullscreen mode Exit fullscreen mode

The init() method

The init() method is a special method that Python runs automatically whenever we create a new instance based on a particular class. This method has two leading underscores and two trailing underscores, a convention that helps prevent Python’s default method names from conflicting with your method names. We define the init() method to have three parameters: self, name, and age. The self parameter is required in the method definition, and it must come first before the other parameters. It simply represent, the instance itself. For example, when we create an instance from the person class, the self attribute simply represents that single instance we have created, giving the individual instance, access to the attributes and methods belonging to the person class.

The two variables defined each have the prefix self. Any variable prefixed with self is available to every method in the class, and we’ll also be able to access these variables through any instance created from the class. The line self.name = name takes the value associated with the parameter name and assigns it to the variable name, which is then attached to the instance being created. The same process happens with self.age = age.

Making an instance from a class

Let’s create a person instance from the person class we just created:

Class Person:
    def __init__(self,name,age):
        self.name = name
        self.age = age
Enter fullscreen mode Exit fullscreen mode

To create an instance, from a class, we’ll create a variable, then assign it to the class with the required parameters.

Let’s create a person with the name ‘Esther’ and age 18. We’ll call the variable person 1.

python
person1 = Person(‘Esther’,18)

The code above will create a person with the name Esther and age 18

We can then display the name and age of the person by accessing the passed attributes using the dot operator.
print(person1.name) will display the name ‘Esther’
print(person1.age) will display the number 18

Dot notation is used often in Python. This syntax demonstrates how
Python finds an attribute’s value. Here Python looks at the instance person1
and then finds the attribute name associated with person1. This is the same attribute referred to as self.name in the class Person. We use the same approach
to work with the attribute age.

Methods

Now let’s implement methods in our person class. Let’s create a simple method that allows the person to talk and say their name. We can create methods the same way we create functions using the def keyword. Each method must also take the self parameter, which is a representation of the instance itself

def talk(self):
    print(fHello my name is {self.name})
Enter fullscreen mode Exit fullscreen mode

Here, we have defined a method called talk, that once called, will print the name of the person instance created, by accessing the name attribute self.name.
So now our person class looks like this:

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

    def talk(self):
        print(fHello my name is {self.name})
Enter fullscreen mode Exit fullscreen mode

We can access the class methods same way we access the attributes using the dot operator.
Let’s create a person instance and call the talk method:

person2 = Person(Mercy,25)

person2.talk()
Enter fullscreen mode Exit fullscreen mode

Here we create a person instance and assign it to the variable person2. We can then access the talk method from the person class.
When we call person2.talk(), the statement ‘Hello my name is Mercy’ will be printed to the screen.

This was only a simple introduction to the concept of classes in python, in later articles, we will continue to dive deeper into the concept of classes, and the cool things we can create with them
But while you wait, here’s a simple cheat sheet to help you get familiar with the concept of classes in python:
Cheetsheet

Top comments (0)