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:
- What is 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 (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 property.
- 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.
- 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
- Name: Jessa
- Sex: Female
- Profession: Software Engineer
- Working: She is working as Software developer in ABC Company
- Study: She study 2 hours a day
Object 2: Jon
- Name: Jon
- Sex: Male
- Profession: Doctor
- Working: He is working as Doctor
- Study: She study 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.
class class_name: '''This is a docstring. I have created a new class''' <statement 1> <statement 2> . . <statement N>
class_name: It is the name of the class
Docstring: 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.
class Person: def __init__(self, name, sex, profession): # data members (instance variables) self.name = name self.sex = sex self.profession = profession # Behavior (instance methods) def show(self): print('Name:', self.name, 'Sex:', self.sex, 'Profession:', self.profession) # Behavior (instance methods) def work(self): print(self.name, 'working as a', self.profession)
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
<object-name> = <class-name>(<arguments>)
Below is the code to create the object of a Person class
jessa = Person('Jessa', 'Female', 'Software Engineer')
The complete example:
class Person: def __init__(self, name, sex, profession): # data members (instance variables) self.name = name self.sex = sex self.profession = profession # Behavior (instance methods) def show(self): print('Name:', self.name, 'Sex:', self.sex, 'Profession:', self.profession) # Behavior (instance methods) def work(self): print(self.name, 'working as a', self.profession) # create object of a class jessa = Person('Jessa', 'Female', 'Software Engineer') # call methods jessa.show() jessa.work()
Name: Jessa Sex: Female Profession: Software Engineer Jessa working as a Software Engineer
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
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:
- A class variable is accessed or modified using the class name
class Student: # class variables school_name = 'ABC School' # constructor def __init__(self, name, age): # instance variables self.name = name self.age = age s1 = Student("Harry", 12) # access instance variables print('Student:', s1.name, s1.age) # access class variable print('School name:', Student.school_name) # Modify instance variables s1.name = 'Jessa' s1.age = 14 print('Student:', s1.name, s1.age) # Modify class variables Student.school_name = 'XYZ School' print('School name:', Student.school_name)
Student: Harry 12 School name: ABC School Student: Jessa 14 School name: XYZ School
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.
Example: Define and call an instance method and class method
# class methods demo class Student: # class variable school_name = 'ABC School' # constructor def __init__(self, name, age): # instance variables self.name = name self.age = age # instance method def show(self): # access instance variables and class variables print('Student:', self.name, self.age, Student.school_name) # instance method def change_age(self, new_age): # modify instance variable self.age = new_age # class method @classmethod def modify_school_name(cls, new_name): # modify class variable cls.school_name = new_name s1 = Student("Harry", 12) # call instance methods s1.show() s1.change_age(14) # call class method Student.modify_school_name('XYZ School') # call instance methods s1.show()
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.
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.
class Demo: pass
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.
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.
Obj.PROPERTY = value
class Fruit: def __init__(self, name, color): self.name = name self.color = color def show(self): print("Fruit is", self.name, "and Color is", self.color) # creating object of the class obj = Fruit("Apple", "red") # Modifying Object Properties obj.name = "strawberry" # calling the instance method using the object obj obj.show() # Output Fruit is strawberry and Color is red
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.
class Fruit: def __init__(self, name, color): self.name = name self.color = color def show(self): print("Fruit is", self.name, "and Color is", self.color) # creating object of the class obj = Fruit("Apple", "red") # Deleting Object Properties del obj.name # Accessing object properties after deleting print(obj.name) # Output: AttributeError: 'Fruit' object has no attribute 'name'
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.
In Python, we can also delete the object by using a
del keyword. An object can be anything like, class object,
Example: Deleting object
class Employee: depatment = "IT" def show(self): print("Department is ", self.depatment) emp = Employee() emp.show() # delete object del emp # Accessing after delete object emp.show() # Output : NameError: name 'emp' is not defined
In the above example, we create the object
emp of the class
Employee. After that, using the
del keyword, we deleted that object.