Let's say I want to implement the following functionality.
I have a class Employee, which has 3 variables viz, name age and salary. I will override the __add__
and use it to create a single object that will be a combination of the two objects used. For example, if I have A and B, and if I do A + B, I want their information to be combined. I am able to do it. But now I want to delete one of the objects, let's say B, so that there won't exist that B Employee in the system. I tried using del, but I can still print its values after deletion.
class Employee:
__slots__ = ['__name', '__age', '__salary']
def __init__(self, name, age, salary):
self.__name = name
self.__age = age
self.__salary = salary
def display(self):
print(f"\nName: {self.__name}")
print(f"Age: {self.__age}")
print(f"Salary: {self.__salary}")
def __add__(self, other):
finalName = f"{self.__name} & {other.__name}"
finalAge = (self.__age + other.__age) / 2
finalSalary = self.__salary + other.__salary
del other
return Employee(finalName, finalAge, finalSalary)
a = Employee("A", 22, 10000)
b = Employee("B", 25, 15000)
a.display()
b.display()
# Prints as expected
Name: A
Age: 22
Salary: 10000
Name: B
Age: 25
Salary: 15000
a = a + b
a.display()
# Additon operations takes place successfully and it prints the following
Name: A & B
Age: 23.5
Salary: 25000
b.display()
# Actual Behaviour
Name: B
Age: 25
Salary: 15000
# Expected Behaviour
Some error saying B does not exist or not defined
with ? (sorry to bother dont have my python machine with me ) – pippo1980 Apr 04 '21 at 18:13