Classes

in Object-Oriented Programming

What is a Class?

A class in Object-Oriented Programming (OOP) is a blueprint for creating objects. It provides a means of bundling data and functionality together. When a class is defined, no memory is allocated. However, when it is instantiated (i.e., an object is created), memory is allocated.

A class is defined in Python using the class keyword:

1class MyClass:
2    pass

The pass statement is a null operation. Here, it is used as a placeholder because Python expects some code to be in the indention block.

Creating an Object

In Python, an object is an instance of a class. We can create an object of a class by calling the class name followed by parentheses and assigning it to a variable.

1class MyClass:
2    pass
3
4my_object = MyClass()

In the code above, my_object is an object (instance) of MyClass.

Attributes and Instance Variables

In a class, attributes are variables that hold data, also known as “fields”. Every instance of a class will have its own copy of these variables, hence they are also known as “instance variables”.

We can define attributes within a method called __init__(). This method will be called when the class is instantiated.

1class MyClass:
2    def __init__(self):
3        self.attribute = "Hello, Codebay!"
4
5my_object = MyClass()
6print(my_object.attribute)

In the code above, attribute is an attribute of MyClass, and self is a reference to the current instance of the class.

Here’s something to keep in mind: although we can technically access and modify attributes directly, as shown above, it’s considered good practice to use getters and setters (methods designed specifically to get and set the values of attributes).

Class Methods

Classes can contain functions, called methods. Methods define the behavior of the instances of the class.

Let’s add a method to our class:

1class MyClass:
2    def __init__(self):
3        self.attribute = "Hello, Codebay!"
4
5    def greet(self):
6        return self.attribute
7
8my_object = MyClass()
9print(my_object.greet())

In the example above, greet is a method of the class MyClass.

Like attributes, to call a method we use the dot (.) operator on the instance of the class.

Also, notice that greet uses self as its first parameter. This is a convention in Python. The instance that the method is being called on is automatically passed as the first parameter (which we typically call self).

You have now learned about classes, one of the most important building blocks of Object-Oriented Programming in Python.