How To Define A Class In Python

In this tutorial, we will learn how to define a class in Python, a powerful feature of OOP (Object-Oriented Programming) that allows you to create your own custom data types. Classes are essentially a blueprint for creating objects with similar properties and methods.

Step 1: The class keyword

The first step in defining a class is using the class keyword, followed by the name of the class. The name of the class should be written in CamelCase (upper camel case) format, where the first letter of each word is capitalized and there are no spaces or underscores between words.

Step 2: Initialize the class

Next, define the class’s constructor using the def keyword with a special method called __init__(). The constructor initializes an object when it is created. This method takes the special parameter self which refers to the instance of the class.

Step 3: Define class attributes

Within the __init__() method, you can set attributes for your class. Attributes are variables associated with the class’s instances. To set an attribute, use the syntax:

For example, let’s define a class called Person with the attributes name and age:

Here, we added the name and age parameters to the __init__() function, allowing us to create Person objects with customized properties.

Step 4: Define class methods

Methods are functions that are associated with a class’s instances. To define a method, use the def keyword, followed by the method’s name and the special parameter self.

For example, let’s add a method called introduce_self() to our Person class that prints the person’s name and age:

Step 5: Create an object of the class

To create an object of your class, simply call the class with its name followed by parentheses, and pass any required parameters to the __init__() method:

Step 6: Access object attributes and methods

Now that you have created an object of your class, you can access its attributes and methods using dot notation. For example:

Full Code:


My name is Alice and I am 29 years old.


In this tutorial, we have learned how to define a class in Python, set attributes, define methods, and create objects of the class. This knowledge is crucial for writing structured and maintainable code in Python, as classes facilitate the clear and concise organization of data and functionality.