Python Classes for Reusable Code Encapsulating Data and Behavior

By:   |   Updated: 2024-06-24   |   Comments   |   Related: > Python


Problem

What are classes in Python? How do classes help to implement object-oriented programming (OOP) concepts?  Can you provide some examples for beginners to help learn Python programming?

Solution

Python is an object-oriented programming language. It supports classes for implementing reusable code encapsulating data and behavior in a single entity. A class is a special construct in Python that acts as a code template for defining and creating objects.

One of Python's key strengths is its versatility. A class is a template that can be used to build multiple objects of the same kind, showcasing the language's flexibility and adaptability. The class defines a class object's states (properties) and methods (behaviors).

Look at the example below of a class named car.

  • The class car has states: make, model, year, and status. The state represents the object attributes.
  • The class car has behaviors: stop() and start(). The behaviour represents the methods applied to the class object.

As shown below, we derived car1 and car2 objects from the car class having different states and behaviors.

Example of a Python class

Python defines the class using the class keyword. The diagram below shows a typical class definition of Python.

  • Class keyword followed by class name abc
  • Def keyword defines a function
  • __init__ is a particular constructor that initializes the object's attributes or states. After the __init__ constructor, we can define the class states inside the brackets.
  • Self keyword is used to reference the current instance of a class. It accesses the class states or behaviour using the dot product, such as self.n.
typical class definition of Python

The following code defines an employee class with name, age, and role states. It has intro() behaviour that prints the employee introduction using a print statement. Here is the syntax:

class employee:
    def __init__(self, name, age, role):
        self.name = name
        self.age = age
        self.role = role
 
    def intro(self):
        print(f"Hello, I am {self.name}, {self.age} years old, working as a {self.role}.")
 

Now, we can create a class object by supplying the input values. Here, we create an object named emp1 from the employee class.

Later, we can access object attributes and methods with the dot notation. For example, empl1.name defines object emp1 name.

# Creating an instance of the employee class
emp1 = employee("john", 35, "database architect")
 
# Accessing attributes and calling methods using self
print(emp1.name) 
print(emp1.age)  
emp1.intro()
create a class object by supplying the input values

Similarly, you can create another object from the employee class, as shown below.

# Creating an instance of the employee class
emp2 = employee("Mohan", 26, "Software developer")
 
# Accessing attributes and calling methods using self
print(emp2.name) 
print(emp2.age)  
emp2.intro()
code sample

Suppose we want to modify the object states after it is declared. For example, let's say we want to change Mohan's age to 28 instead of 26. It changes the state using the code line emp2.age = 28.

The code below shows the before and after values of the employee state.

#before 
emp2 = employee("Mohan", 26, "Software developer")
emp2.intro()
 
#after
emp2.age = 28
emp2.intro()
code sample

Class Variables

The class variable is declared inside a class but outside of the __init__ method. It is bound to a class but shared by all its objects. We can access these variables using the class name.variable.

In the code below, we defined a class variable named organization_name and set its value. We then used the instance variable in the introduction using employee.organization_name.

class employee:
    #class variable
    organization_name = "XYZ Corp."
    def __init__(self, name, age, role):
        self.name = name
        self.age = age
        self.role = role
 
    def intro(self):
        print(f"Hello, I am {self.name}, {self.age} years old, working as a {self.role} in {employee.organization_name}")
 
# Creating an instance of the employee class
emp1 = employee("john", 35, "database architect")
 
# Accessing attributes and calling methods using self
print(emp1.name) 
print(emp1.age)  
emp1.intro()
Class variables

You can modify or set the class variable value and use it for subsequent objects. For example, we can modify the emp2 organization name to "ABC Inc".

employee.organization_name="ABC Inc."
# Creating an instance of the employee class
emp2 = employee("Mohan", 26, "Software developer")
 
# Accessing attributes and calling methods using self
print(emp2.name) 
print(emp2.age)  
emp2.intro()
code sample

Instance Method and Class Method in Python Classes

A Python class can be defined using the following methods:

  • Instance method
    • It can read or modify the object state.
    • It uses the self as a first parameter to represent the instance.
    • It can access the state or behaviour using "self."

We have explained the instance method in the previous examples.

  • Class method
    • It operates on the class instead of the instance of the class.
    • It takes cls as the first parameter.
    • It can be used to create or modify class variables or constructors.

The example below contains both instance and class methods, where:

  • The class method definition starts with the keyword @classmethod.
  • Its first parameter is cls, and we access the class variable as cls.organization_name and assign a new value obtained from the new_org parameter.
  • For object emp2, we call the class variable to change the employee organization name and print it later.
class employee:
    #class variable
    organization_name = "XYZ Corp."
    def __init__(self, name, age, role):
        self.name = name
        self.age = age
        self.role = role
 
    def intro(self):
        print(f"Hello, I am {self.name}, {self.age} years old, working as a {self.role} in {employee.organization_name}")
 
    #class method
    @classmethod
    def modify_organization_name(cls, new_org):
        cls.organization_name = new_org
 
# Creating an instance of the employee class
emp1 = employee("john", 35, "database architect")
 
# Accessing attributes and calling methods using self
emp1.intro()
 
#calling class method
employee.modify_organization_name("ABC Inc")
 
emp2 = employee("Mohan", 26, "Software developer")
 
emp2.intro()
output

Dynamically Add Instance Variable to an Object

Suppose we created a class and defined the instance variables after the self parameter. Later, if we want to add an instance variable for a specific object, we can add it dynamically from outside the class.

Below, we added the instance variable location for the emp2 object of the employee class.

class employee:
    def __init__(self, name, age, role):
        self.name = name
        self.age = age
        self.role = role
 
#before 
emp2 = employee("Mohan", 26, "Software developer")
print('Name:',emp2.name, 'age:',emp2.age,'Role:',emp2.role)
 
# add new instance variable 'Location' to employee class
emp2.location = "London"
 
#after
print('Name:',emp2.name, 'age:',emp2.age,'Role:',emp2.role, 'location:',emp2.location)
code sample

Note: We cannot add an instance object dynamically for a class; it can be added only for particular objects.

Listing All Instance Variables of an Object

We can use the __dict__ function to get a list of instance variables. It returns the key and its value.

class employee:
    def __init__(self, name, age, role):
        self.name = name
        self.age = age
        self.role = role
 
emp2 = employee("Mohan", 26, "Software developer")
print(emp2.__dict__)

As shown below, it gives the key and its value for the object of a class.

code sample

We can use __dict__items() to return the key value specifically.

# Get each instance variable
for key_value in emp2.__dict__.items():
    print(key_value[0], '=', key_value[1])
code sample
Next Steps
  • Stay tuned for more Python tutorials in upcoming tips.
  • Explore existing Python tips on MSSQLTips.


sql server categories

sql server webinars

subscribe to mssqltips

sql server tutorials

sql server white papers

next tip



About the author
MSSQLTips author Rajendra Gupta Rajendra Gupta is a Consultant DBA with 14+ years of extensive experience in database administration including large critical OLAP, OLTP, Reporting and SharePoint databases.

This author pledges the content of this article is based on professional experience and not AI generated.

View all my tips


Article Last Updated: 2024-06-24

Comments For This Article

















get free sql tips
agree to terms