Python | Ejemplo para poner en práctica destructor y constructores utilizando __del __ () y __init __ ()

Aquí, vamos a aprender cómo implementar destructor y constructores que utilizan __del __ () y __init __ () en Python ?

Para implementar un constructor, utilizamos __init () __ e implementar un destructor, utilizamos __del () __ en Python.

Programa:

class Employee:
def __init__(self): #Constructor
self.__id = 0
self.__name = ""
self.__gender = ""
self.__city = ""
self.__salary = 0
print("Object Initialized.")
def __del__(self): #Destructor
print("Object Destroyed.")
def setData(self):
self.__id=int(input("Enter Idt:"))
self.__name = input("Enter Namet:")
self.__gender = input("Enter Gender:")
self.__city = input("Enter Cityt:")
self.__salary = int(input("Enter Salary:"))
def showData(self):
print("Idtt:",self.__id)
print("Namet:", self.__name)
print("Gendert:", self.__gender)
print("Cityt:", self.__city)
print("Salaryt:", self.__salary)
def main():
#Employee Object
emp=Employee()
#emp.setData()
emp.showData()
if __name__=="__main__":
main()

salida

Object Initialized.
Id : 0
Name :
Gender :
City :
Salary : 0
Object Destroyed.

utilizando __str__ método

En este programa estamos la implementación de la función str usando __str __ ( ) . Esta función devuelve una cadena cada vez que pase objeto class ‘s a de impresión () función.

# employee class code in Python
# class definition
class Employee:
def __init__(self): #Constructor
self.__id = 0
self.__name = ""
self.__gender = ""
self.__city = ""
self.__salary = 0
print("Object Initialized.")
def __del__(self): #Destructor
print("Object Destroyed.")
def setData(self):
self.__id=int(input("Enter Idt:"))
self.__name = input("Enter Namet:")
self.__gender = input("Enter Gender:")
self.__city = input("Enter Cityt:")
self.__salary = int(input("Enter Salary:"))
def __str__(self):
data = "["+str(self.__id)+","+self.__name+","+self.__gender+","+self.__city+","+str(self.__salary)+"]"
return data
def showData(self):
print("Idtt:",self.__id)
print("Namet:", self.__name)
print("Gendert:", self.__gender)
print("Cityt:", self.__city)
print("Salaryt:", self.__salary)
def main():
#Employee Object
emp=Employee()
emp.setData()
emp.showData()
print(emp)
if __name__=="__main__":
main()

salida

Object Initialized.
Enter Id :101
Enter Name :Pankaj
Enter Gender:Male
Enter City :Delhi
Enter Salary:70000
Id : 101
Name : Pankaj
Gender : Male
City : Delhi
Salary : 70000
[101,Pankaj,Male,Delhi,70000]
Object Destroyed.


Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *