Python Program on Getters and Setters

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

In the dynamic landscape of Python programming, the utilization of getters and setters adds a layer of control and flexibility to class attributes. These mechanisms play a pivotal role in encapsulating the access and modification of private attributes within a class, promoting the principles of data encapsulation and abstraction. Getters retrieve the values of private attributes, while setters provide a controlled interface for modifying them. This article delves into the practical aspects of implementing getters and setters in Python, unraveling their significance in building robust and secure.

Topic Explanation:

At the heart of object-oriented programming, the concept of getters and setters empowers developers to exercise precise control over the interaction with class attributes.

In Python, a language celebrated for its simplicity and readability, the implementation of these methods offers a practical means to enforce encapsulation. Getters, also known as accessor methods, enable the retrieval of private attribute values, ensuring that access to sensitive data occurs through a predefined interface. On the flip side, setters, or mutator methods, govern the modification of these attributes, allowing developers to impose validation logic and maintain data integrity.

The real-world application of getters and setters becomes evident in scenarios where certain attributes require controlled access or validation checks. For instance, ensuring that an employee’s salary remains within a specific range or that a password adheres to security standards can be efficiently handled through the implementation of setters.

This article will explore concrete examples of using getters and setters, providing insights into their practical implementation and highlighting the enhanced security and maintainability they bring to Python codebases. As we navigate through these practical aspects, developers will gain a deeper understanding of how getters and setters contribute to the robustness and clarity of their Python.

Prerequisites:

Object-Oriented Programming (OOP):

  • Familiarity with OOP concepts, especially classes, objects, and encapsulation.

Python Classes and Attributes:

  • Understanding of how to define classes and create attributes.
  • Knowledge of instance variables and encapsulation principles.

Basic Python Syntax:

  • Proficiency in basic Python syntax.
  • Understanding of function definitions, method calls, and variable assignments.

Property Decorators:

  • Awareness of property decorators in Python, as getters and setters are often implemented using the @property and @<attribute>.setter decorators.

Object Encapsulation:

  • Understanding the concept of encapsulation and the reasons for using getters and setters to control access to class attributes.

Code with Comments:

# Define a class named "Employee"
class Employee:
    # Constructor (__init__ method) to initialize object attributes
    def __init__(self, eid, ename, esal):
        self.eid = eid  # Instance variable for Employee ID
        self.ename = ename  # Instance variable for Employee Name
        self.esal = esal  # Instance variable for Employee Salary

    # Define a custom string representation for the object
    def __str__(self):
        s = "ID={} NAME={} SALARY={}"
        # Format the string with the values of Employee ID, Name, and Salary
        s = s.format(self.eid, self.ename, self.esal)
        # Return the formatted string
        return s

# Prompt the user to input Employee details
myid = int(input("Enter Employee Id: "))  # Take user input for Employee ID
myname = input("Enter Employee Name: ")  # Take user input for Employee Name
mysal = int(input("Enter Employee Salary: "))  # Take user input for Employee Salary

# Create an instance of the Employee class with the provided input
E1 = Employee(myid, myname, mysal)

# Print the string representation of the Employee object
print(E1)

Output:
Enter Employee Id: 202
Enter Employee Name: Alice Johnson
Enter Employee Salary: 65000
ID=202 NAME=Alice Johnson SALARY=65000

Code Explanation:

Class Employee:

Attributes (eid, ename, esal): These represent the Employee ID, Name, and Salary, respectively. Attributes encapsulate data within the class.

Methods:

__init__: The constructor method initializes the Employee object with the provided values for ID, Name, and Salary. It sets the instance variables (self.eid, self.ename, self.esal).
__str__: This method defines a custom string representation for the Employee object. It formats and returns a string containing the Employee ID, Name, and Salary.

User Input:

input(): This function takes user input as a string.
int(): Converts the user input to an integer when necessary, ensuring data type consistency.
Object Creation and Usage:

E1 = Employee(myid, myname, mysal): This line creates an instance of the Employee class (E1) by calling the constructor with the user-provided input values. It initializes the Employee object with the entered ID, Name, and Salary.

Printing Output:

print(E1): The print statement displays the string representation of the Employee object. The __str__ method is automatically invoked when printing, presenting a formatted output with the Employee’s details.

Commented Code (MyClass):

The commented-out code presents another class (MyClass) with a similar structure. It demonstrates the versatility of class creation, including a constructor and __str__ method, though it remains inactive in the current execution. This illustrates the potential for creating multiple classes and objects within a Python script.

Code 2 with Comments:

# Define a class named "Employee"
class Employee:
    # Methods for setting and getting employee attributes
    def setId(self, id):
        self.id = id

    def getId(self):
        return self.id

    def setName(self, name):
        self.name = name

    def getName(self):
        return self.name

    def setSalary(self, sal):
        self.sal = sal

    def getSalary(self):
        return self.sal

    def setDepartment(self, dept):
        self.dept = dept

    def getDepartment(self):
        return self.dept

# Prompt user to input Employee details
myid = int(input("Enter Employee Id: "))
myname = input("Enter Employee Name: ")
mysal = int(input("Enter Employee Salary: "))

# Create an instance of the Employee class
E1 = Employee()

# Set employee attributes using setter methods
E1.setId(myid)
E1.setName(myname)
E1.setSalary(mysal)

# Print employee details using getter methods
print("Id=", E1.getId())
print("Name=", E1.getName())
print("Salary=", E1.getSalary())

Output For code 2:

Enter Employee Id: 101
Enter Employee Name: John Doe
Enter Employee Salary: 50000

Id= 101
Name= John Doe
Salary= 50000

Code 2 with Explanation:

Class Employee:

Methods:

setId: Setter method to set the Employee ID attribute.
getId: Getter method to retrieve the Employee ID.
setName: Setter method to set the Employee Name attribute.
getName: Getter method to retrieve the Employee Name.
setSalary: Setter method to set the Employee Salary attribute.
getSalary: Getter method to retrieve the Employee Salary.
setDepartment: Setter method to set the Employee Department attribute (not currently used).
getDepartment: Getter method to retrieve the Employee Department (not currently used).

User Input:

input(): Takes user input for Employee ID, Name, and Salary.
int(): Converts input to an integer where necessary.

Object Creation and Attribute Setting:

E1 = Employee(): Creates an instance of the Employee class (E1).
Attribute setting using setter methods (setId, setName, setSalary).

Printing Output: Printing Employee details using getter methods (getId, getName, getSalary). Outputs the formatted details of the entered employee information.

Conclusion:

In conclusion, the exploration of getters and setters in Python underscores their pivotal role in fostering secure and controlled access to class attributes. Through the examples provided, we witnessed how the Employee class seamlessly integrates these mechanisms to manage Employee ID, Name, and Salary.

The concise and well- organized syntax of getters and setters enhances code clarity, enforcing data encapsulation and abstraction principles. The user interactions showcase the practical utility of these methods, ensuring a standardized approach to attribute manipulation.

Furthermore, the flexibility demonstrated by the Employee class in accommodating additional features like departmental information exemplifies the extensibility offered by getters and setters. Overall, the article unveils the practical application of these techniques, empowering Python developers to create robust and maintainable code structures.

Your opinion matters
Please write your valuable feedback about DataFlair on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *