Classes and Objects in Python (2024)

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?
  • Create a Class in Python
  • Create Object of a Class
  • Class Attributes
  • Class Methods
  • Class Naming Convention
  • pass Statement in Class
  • Object Properties
    • Modify Object Properties
    • Delete object properties
  • Delete Objects

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.

Classes and Objects in Python (1)

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

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 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)Code language: Python (python)

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:

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 classjessa = Person('Jessa', 'Female', 'Software Engineer')# call methodsjessa.show()jessa.work()Code language: Python (python)

Output:

Name: Jessa Sex: Female Profession: Software EngineerJessa 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.
Classes and Objects in Python (2)

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

class Student: # class variables school_name = 'ABC School' # constructor def __init__(self, name, age): # instance variables self.name = name self.age = ages1 = Student("Harry", 12)# access instance variablesprint('Student:', s1.name, s1.age)# access class variableprint('School name:', Student.school_name)# Modify instance variabless1.name = 'Jessa's1.age = 14print('Student:', s1.name, s1.age)# Modify class variablesStudent.school_name = 'XYZ School'print('School name:', Student.school_name)Code language: Python (python)

Output

Student: Harry 12School name: ABC SchoolStudent: Jessa 14School name: XYZ School

Class Methods

InObject-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 useinstance variablesinside a method, such methods are called instance methods.
  • Class method: Used to access or modify the class state. In method implementation, if we use onlyclass 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.
Classes and Objects in Python (3)

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 classand 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

# class methods democlass 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_names1 = Student("Harry", 12)# call instance methodss1.show()s1.change_age(14)# call class methodStudent.modify_school_name('XYZ School')# call instance methodss1.show()Code language: Python (python)

Output

Student: Harry 12 ABC SchoolStudent: 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: 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 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.

Classes and Objects in Python (4)

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 = valueCode language: Python (python)

Example

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 classobj = Fruit("Apple", "red")# Modifying Object Propertiesobj.name = "strawberry"# calling the instance method using the object objobj.show()# Output Fruit is strawberry and Color is redCode language: Python (python)

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 classobj = Fruit("Apple", "red")# Deleting Object Propertiesdel obj.name# Accessing object properties after deletingprint(obj.name)# Output: AttributeError: 'Fruit' object has no attribute 'name'Code language: Python (python)

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_nameCode language: Python (python)

Example: Deleting object

class Employee: depatment = "IT" def show(self): print("Department is ", self.depatment)emp = Employee()emp.show()# delete objectdel emp# Accessing after delete objectemp.show()# Output : NameError: name 'emp' is not defined Code language: Python (python)

In the above example, we create the object emp of the class Employee. After that, using the del keyword, we deleted that object.

Classes and Objects in Python (2024)

References

Top Articles
Latest Posts
Article information

Author: Arielle Torp

Last Updated:

Views: 6242

Rating: 4 / 5 (41 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Arielle Torp

Birthday: 1997-09-20

Address: 87313 Erdman Vista, North Dustinborough, WA 37563

Phone: +97216742823598

Job: Central Technology Officer

Hobby: Taekwondo, Macrame, Foreign language learning, Kite flying, Cooking, Skiing, Computer programming

Introduction: My name is Arielle Torp, I am a comfortable, kind, zealous, lovely, jolly, colorful, adventurous person who loves writing and wants to share my knowledge and understanding with you.