Python is an object-oriented programming language. This means that almost all the code is implemented using a special construct called classes. A class is a code template for creating objects.
After reading this article, you will learn:
- Class and objects in Python
- Class attributes and methods
- Creating and accessing object properties
- Modify and delete an object
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 an attribute that represents a state of an object, and it also reflects the property of an object.
- Behavior: An object has methods that represent its behavior.
Python is an Object-Oriented Programming language, so everything in Python is treated as an object. An object is a real-life entity. It is the collection of various data and functions that operate on those data.
For example, If we design a class based on the states and behaviors of a Person, then States can be represented as instance variables and behaviors as class 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 a male, and he is a lawyer. Here, both objects are created from the same class, but they have different states and behaviors.
Create a Class in Python
In Python, class is defined by using the class
keyword. 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
An object is essential to work with the class attributes. The object is created using the class name. When we create an object of the class, it is called instantiation. The object is also called the instance of a 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, Object creation is divided into two parts in Object Creation and Object initialization
- Internally, the
__new__
is the method that creates the object - And, using the
__init__()
method we can implement constructor to initialize the object.
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
Class Attributes
When we design a class, we use instance variables and class variables.
In Class, attributes can be defined into two parts:
- 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 do not share instance attributes. Instead, every object has its copy of the instance attribute and is unique to each object.
All instances of a class share the class variables. However, unlike instance variables, the value of a class variable is not varied from object to object.
Only one copy of the static variable will be created and 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 accessed or modified using the class name
Example
Output
Student: Harry 12 School name: ABC School Student: Jessa 14 School name: XYZ School
Class Methods
In Object-oriented programming, Inside a Class, we can define the following three types of methods.
- 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. Inside this method, we don’t use instance or class variable because this static method doesn’t have access to the class attributes.
Instance methods work on the instance level (object level). For example, if we have two objects created from the student class, They may have different names, marks, roll numbers, etc. Using instance methods, we can access and modify the instance variables.
A class method is bound to the class and not the object of the class. It can access only class variables.
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 are essential in any programming language for better readability. If we give a sensible name, it will save our time and energy later. Writing readable code is one of the guiding principles of the Python language.
We should follow specific rules while we are deciding a name for the class in Python.
- Rule-1: Class names should follow the UpperCaseCamelCase convention
- Rule-2: Exception classes should end in “Error“.
- Rule-3: If a class is callable (Calling the class from somewhere), in that case, we can give a class name like a function.
- Rule-4: Python’s built-in classes 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.
The pass
statement is used to have an empty block in a code because the empty code is not allowed in loops, function definition, class definition. Thus, the pass
statement will results in no operation (NOP). Generally, we use it as a placeholder when we do not know what code to write or add code in a future release.
For example, suppose we have a class that is not implemented yet, but we want to implement it in the future, and they cannot have an empty body because the interpreter gives an error. So use the pass
statement to construct a body that does nothing.
Example
class Demo:
pass
Code 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 with it. In other words, we can say that object property is an association between name and value.
For example, a car is an object, and its properties are car color, sunroof, price, manufacture, model, engine, and so on. Here, color is the name and red is the value. Object properties are nothing but instance variables.
Modify Object Properties
Every object has properties associated with them. We can set or modify the object’s properties after object initialization by calling the property directly using the dot operator.
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.
In the above example, As we can see, the attribute name has been deleted when we try to print or access that attribute gets an error message.
Delete Objects
In Python, we can also delete the object by using a del
keyword. An object can be anything like, class object, list
, tuple
, set
, etc.
Syntax
del object_name
Code 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.