Python is an object-oriented programming language. In Python, you organize data and the code that works on it using classes. A class is a code template for creating objects.
After reading this article, you will learn:
- Class and objects in Python, and what
selfmeans - Class attributes and methods
- Creating and accessing object properties
- Modify and delete an object, and control how it is printed with
__str__()and__repr__()
Table of contents
What is a Class and Objects in Python?
- Class: The class is a user-defined data structure that binds the data members and methods into a single unit. Class is a blueprint or code template for object creation. Using a class, you can create as many objects as you want.
- Object: An object is an instance of a class. It is a collection of attributes (variables) and methods. We use the object of a class to perform actions.
Objects have two characteristics: They have states and behaviors (an object has attributes and methods attached to it). Attributes represent its state, and methods represent its behavior. Using its methods, we can modify its state.
In short, every object has the following properties:
- Identity: Every object must be uniquely identified.
- State: An object has attributes that represent its state, or its data.
- Behavior: An object has methods that represent its behavior.
In Python, everything is an object: numbers, strings, lists, functions, and the objects you create from your own classes. An object often models a real-life entity. It bundles data together with the functions that operate on that data.
For example, If we design a class based on the states and behaviors of a Person, its states can be represented as instance variables and its behaviors as methods.

A real-life example of class and objects.
Class: Person
- State: Name, Sex, Profession
- Behavior: Working, Study
Using the above class, we can create multiple objects that depict different states and behavior.
Object 1: Jessa
- State:
- Name: Jessa
- Sex: Female
- Profession: Software Engineer
- Behavior:
- Working: She is working as a software developer at ABC Company
- Study: She studies 2 hours a day
Object 2: Jon
- State:
- Name: Jon
- Sex: Male
- Profession: Doctor
- Behavior:
- Working: He is working as a doctor
- Study: He studies 5 hours a day
As you can see, Jessa is female, and she works as a Software engineer. On the other hand, Jon is male, and he works as a doctor. Here, both objects are created from the same class, but they have different states and behaviors.
Create a Class in Python
In Python, a class is defined using the class keyword, followed by the class name and a colon. The syntax to create a class is given below.
Syntax
class class_name:
'''This is a docstring. I have created a new class'''
<statement 1>
<statement 2>
.
.
<statement N>Code language: Python (python)
class_name: It is the name of the classDocstring: It is the first string inside the class and has a brief description of the class. Although not mandatory, this is highly recommended.statements: Attributes and methods
Example: Define a class in Python
In this example, we are creating a Person Class with name, sex, and profession instance variables.
Create Object of a Class
To use a class, you create objects from it. You create an object by calling the class name like a function. Creating an object is called instantiation, and the object is also called an instance of the class.
A constructor is a special method used to create and initialize an object of a class. This method is defined in the class.
In Python, creating an object happens in two steps: object creation and object initialization.
- Internally, the
__new__is the method that creates the object - Then, the
__init__()method initializes it, for example, by setting its instance variables. This is the method you usually write yourself.
Read More: Constructors in Python
Syntax
<object-name> = <class-name>(<arguments>) Code language: Python (python)
Below is the code to create the object of a Person class
jessa = Person('Jessa', 'Female', 'Software Engineer')Code language: Python (python)
The complete example:
Output:
Name: Jessa Sex: Female Profession: Software Engineer Jessa working as a Software Engineer
What is self in Python?
Every instance method, including __init__(), takes self as its first parameter. self refers to the object on which the method is called, so self.name means “the name attribute of this particular object”.
You never pass self yourself. When you write jessa.show(), Python automatically calls Person.show(jessa), passing the object as self. The name self is a convention, not a keyword, but you should always use it.
Class Attributes
When we design a class, we use instance variables and class variables.
A class can have two kinds of attributes:
- Instance variables: The instance variables are attributes attached to an instance of a class. We define instance variables in the constructor ( the
__init__()method of a class). - Class Variables: A class variable is a variable that is declared inside of class, but outside of any instance method or
__init__()method.

Objects don’t share instance attributes. Every object has its own copy, with values unique to that object.
Class variables, on the other hand, are shared by all instances of the class. Unlike instance variables, their value is the same for every object.
Only one copy of a class variable exists, and it is shared between all objects of the class.
Accessing properties and assigning values
- An instance attribute can be accessed or modified by using the dot notation:
instance_name.attribute_name. - A class variable is read with the class name (
ClassName.variable) or through an object, but it should be modified using the class name. Assigning through an object creates a new instance variable instead.
Example
Output
Student: Harry 12 School name: ABC School Student: Jessa 14 School name: XYZ School
Class Methods
In Object-oriented programming, you can define the following three types of methods inside a class.
- Instance method: Used to access or modify the object state. If we use instance variables inside a method, such methods are called instance methods.
- Class method: Used to access or modify the class state. In method implementation, if we use only class variables, then such type of methods we should declare as a class method.
- Static method: It is a general utility method that performs a task in isolation. It receives neither
selfnorcls, so it can’t access instance or class variables directly. Define it with the@staticmethoddecorator.

Instance methods work on the instance level (object level). For example, two objects created from the Student class may have different names, marks, roll numbers, and so on. Using instance methods, we can access and modify the instance variables.
A class method is bound to the class and not to an object. It receives the class as its first argument (cls), so it can access and modify class variables, but not instance variables. Define it with the @classmethod decorator.
Read More: Python Class Method vs. Static Method vs. Instance Method
Example: Define and call an instance method and class method
Output
Student: Harry 12 ABC School Student: Harry 14 XYZ School
Class Naming Convention
Naming conventions make code easier to read in any programming language. Sensible names save time and effort later, and readable code is one of the guiding principles of Python (see the PEP 8 style guide).
Follow these conventions when naming a class in Python:
- Rule-1: Class names should follow the UpperCamelCase (also called PascalCase) convention, for example,
PersonorBankAccount. - Rule-2: Exception classes should end in “Error“.
- Rule-3: If a class is mainly used like a function (it is called directly and behaves like one), it may be named in lowercase, like a function.
- Rule-4: Python’s built-in classes, such as
int,list, anddict, are typically lowercase words.
pass Statement in Class
In Python, the pass is a null statement. Therefore, nothing happens when the pass statement is executed.
Python doesn’t allow empty blocks in loops, function definitions, or class definitions. The pass statement fills such a block without doing anything (it is a “no operation”). It is generally used as a placeholder for code you plan to add later.
For example, suppose you want to define a class now but implement it later. A class can’t have an empty body, so use pass to give it a body that does nothing.
Example
class Demo:
passCode language: Python (python)
In the above example, we defined class without a body. To avoid errors while executing it, we added the pass statement in the class body.
Object Properties
Every object has properties. An object property is an association between a name and a value.
For example, a car is an object, and its properties are color, sunroof, price, manufacturer, model, engine, and so on. In color = "red", color is the name and red is the value. Object properties are nothing but instance variables.

Modify Object Properties
You can set or modify an object’s properties after it is created by assigning to them directly with the dot operator.
object_name.property_name = valueCode language: Python (python)
Example
Delete object properties
We can delete the object property by using the del keyword. After deleting it, if we try to access it, we will get an error.
The attribute name has been deleted, so trying to access it raises an AttributeError.
Delete Objects
You can also delete an object using the del keyword. This works for any object, such as an object of your own class, a list, a tuple, or a set. Strictly speaking, del deletes the variable name. Python frees the object’s memory once no variable refers to it anymore.
Syntax
del object_nameCode language: Python (python)
Example: Deleting object
In the above example, we create the object emp of the class Employee. After that, using the del keyword, we deleted that object.
String representation of an object
If you print an object of your own class, Python shows something like <__main__.Book object at 0x7f...>, which isn’t very useful. Define the special methods __str__() and __repr__() to control how your objects are displayed:
__str__()returns a friendly, readable string. It is used byprint()andstr().__repr__()returns an unambiguous string for developers, ideally one that looks like the code that creates the object. It is used in the interactive shell and when the object is inside a list.
Output:
Python Basics by Jessa
Book('Python Basics', 'Jessa')
[Book('Python Basics', 'Jessa')]
Useful built-in functions for objects
isinstance(obj, ClassName)checks whether an object was created from a class (or one of its subclasses).type(obj)returns the class of an object.hasattr(),getattr(), andsetattr()check, read, and set an attribute by its name as a string.vars(obj)returns a dictionary of the object’s instance attributes.
Summary
- A class is a blueprint, and an object is an instance created from it. Create a class with the
classkeyword and an object by calling the class like a function. - The
__init__()method initializes a new object, andselfrefers to the object itself. - Instance variables belong to one object. Class variables are shared by all objects of the class.
- A class can have instance methods, class methods (
@classmethod), and static methods (@staticmethod). - Use the dot operator to read and modify attributes, and
delto delete attributes or objects. - Define
__str__()and__repr__()to give your objects a readable representation.
