F.E. PPS Unit 5 Practical 3 solution

Practical 3: Program to illustrate the use of the __int__() method to define a custom behavior for conversion to an integer.

Problem Statement

Write a Python program to illustrate the use of the __int__() method to define a custom behavior for conversion to an integer.

Solution Code

				
					class Employee:
    def __init__(self, salary):
        self.salary = salary

    def __int__(self):
        return int(self.salary)

# Creating an object of Employee class
emp1 = Employee(5000.75)

# Converting the object to integer using __int__() method
salary_int = int(emp1)
print(f"Employee Salary as Integer: {salary_int}")


				
			

Output

The program should convert the object emp1 to an integer, using the __int__() method and display the result.

Example Output

				
					Employee Salary as Integer: 5000
Process finished with exit code 0
				
			

Explanation

Below is the explanation of F.E. PPS Unit 5 Practical 3 solution where we have written Python program to illustrate the use of the __int__() method to define a custom behavior for conversion to an integer.

  • Below is the explanation of F.E. PPS Unit 5 Practical 3 solution where we have written Python program to illustrate the use of the __int__() method to define a custom behavior for conversion to an integer
  • __int__() Method: This is a special method used to define the behavior of the int() function when applied to the class object.
  • The __int__() method returns the integer value of the salary attribute.

Key Concepts Learned

  • Custom Type Conversion (__int__())
    • You can define custom conversion logic for converting an object to an integer.
Tech Amplifier Final Logo