Python | 使用__del __()和__init __()实现析构函数和构造函数的示例
To implement a constructor, we use __init()__ and to implement a destructor, we use __del()__ in python.
為了實現構造函數,我們使用__init()__ ;為了實現析構函數,我們使用python中的__del()__ 。
Program:
程序:
class Employee:def __init__(self): #Constructorself.__id = 0self.__name = ""self.__gender = ""self.__city = ""self.__salary = 0print("Object Initialized.")def __del__(self): #Destructorprint("Object Destroyed.")def setData(self):self.__id=int(input("Enter Id\t:"))self.__name = input("Enter Name\t:")self.__gender = input("Enter Gender:")self.__city = input("Enter City\t:")self.__salary = int(input("Enter Salary:"))def showData(self):print("Id\t\t:",self.__id)print("Name\t:", self.__name)print("Gender\t:", self.__gender)print("City\t:", self.__city)print("Salary\t:", self.__salary)def main():#Employee Objectemp=Employee()#emp.setData()emp.showData()if __name__=="__main__":main()Output
輸出量
Object Initialized. Id : 0 Name : Gender : City : Salary : 0 Object Destroyed. .minHeight{min-height: 250px;}@media (min-width: 1025px){.minHeight{min-height: 90px;}} .minHeight{min-height: 250px;}@media (min-width: 1025px){.minHeight{min-height: 90px;}}by using __str__ method
通過使用__str__方法
In this program we are implementing str function using __str__(). This function returns a string whenever we pass class's object to print() function.
在此程序中,我們使用__str __() 實現str函數 。 每當我們將類的對象傳遞給print()函數時,此函數都會返回一個字符串。
# employee class code in Python # class definition class Employee:def __init__(self): #Constructorself.__id = 0self.__name = ""self.__gender = ""self.__city = ""self.__salary = 0print("Object Initialized.")def __del__(self): #Destructorprint("Object Destroyed.")def setData(self):self.__id=int(input("Enter Id\t:"))self.__name = input("Enter Name\t:")self.__gender = input("Enter Gender:")self.__city = input("Enter City\t:")self.__salary = int(input("Enter Salary:"))def __str__(self):data = "["+str(self.__id)+","+self.__name+","+self.__gender+","+self.__city+","+str(self.__salary)+"]"return datadef showData(self):print("Id\t\t:",self.__id)print("Name\t:", self.__name)print("Gender\t:", self.__gender)print("City\t:", self.__city)print("Salary\t:", self.__salary)def main():#Employee Objectemp=Employee()emp.setData()emp.showData()print(emp)if __name__=="__main__":main()Output
輸出量
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.翻譯自: https://www.includehelp.com/python/implement-destructor-and-constructors-using-__del__-and-__init__.aspx
總結
以上是生活随笔為你收集整理的Python | 使用__del __()和__init __()实现析构函数和构造函数的示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: node js 开发网站_使用Node
- 下一篇: 什么是bcd码数据传输通讯_传输障碍|