आपकी ऑफलाइन सहायता

BACK
49

सी प्रोग्रामिंग

149

पाइथन प्रोग्रामिंग

49

सी प्लस प्लस

99

जावा प्रोग्रामिंग

149

जावास्क्रिप्ट

49

एंगुलर जे.एस.

69

पी.एच.पी.
माय एस.क्यू.एल.

99

एस.क्यू.एल.

Free

एच.टी.एम.एल.

99

सी.एस.एस.

149

आर प्रोग्रामिंग

39

जे.एस.पी.





डाउनलोड पी.डी.एफ. ई-बुक्स
Python - Python Constructor and Destructor

Constructor in Python

Python के अलावा C++ और Java में भी Constructor होता है लेकिन उन constructor में खुद class के नाम से ही constructor को बनाया जाता है |

लेकिन Python में Constructor को create करने के लिए __init__() function का इस्तेमाल किया जाता है |

जब class में __init__() function define किया जाता है और उस class का object बनाया जाता है तब ये function automatically call हो जाता है | उसे अलग से call करने की जरुरत नहीं पड़ती है |


Syntax for Constructor in Python

class className:
	class_body(Optional)
	def __init__(parameter(s)):  #Constructor
		constructor_body
	class_body(Optional)

Example for Constructor in Python

Example में MyClass में Constructor को define किया गया है और उसके बाद class के 'obj' call किया गया है | object create होते ही constructor call होता है |

Constructor का इस्तेमाल सामान्यतः variables को initialize करने के लिए किया जाता है |

Source Code :
class MyClass:
    def __init__(self, a, b):
        self.a = a
        self.b = b
        print(self.a,self.b)
        print("Constructor invoked")

obj = MyClass(4, "Hello")
Output :
4 Hello
Constructor invoked



Destructor in Python

C++ और Java में destructor को ~(tilde) sign के साथ class के नाम की जरुरत पड़ती और वो object बनते ही अपने आप call होता है |
लेकिन Python में Destructor के लिए '___del__()' function का इस्तेमाल किया जाता है और जब class का object बनाया जाता है तब वो automatically call नहीं होता है |
Destructor को destroy करने के लिए 'del' operator से object को delete करना पड़ता है |

Example for Destructor in Python

Source Code :
class MyClass:
    def __init__(self, a, b):
        self.a = a
        self.b = b
        print(self.a,self.b)
        print("Constructor invoked")
    def __del__(self):
        print("Destructor invoked")
    
if __name__ == "__main__":              
    obj = MyClass(4, "Hello")
    del obj
Output :
4 Hello
Constructor invoked
Destructor invoked