पिछले topics में आपने Python में classes के बारे में पढ़ा इस topic में आप class constructor के बारे में पढ़ेंगे।


class में एक __init__() function होता है , जो class का object बनने पर automatically run होता है। इस constructor कहते हैं। हालाँकि class में define करें ये जरूरी नहीं होता है।

Python __init__() Example

Copy Fullscreen Close Fullscreen Run
class myClass :
  def __init__(self) :
    print('Object initialized')

myobj = myClass()
Output
C:\Users\Rahulkumar\Desktop\python>python oop_ex.py
Object initialized

जैसे कि example में आप देख सकते हैं कि __init__() function को कही भी call नहीं किया गया है , object create होते ही यह automatically call हुआ है।

Important

Python में defined हर एक function में एक by default parameter pass होता है , जो कि current class object होता है। इसकी help से हम class के अंदर सभी class variables और functions को access करते हैं।


example में आप देख सकते हैं , function में self name का parameter लिया गया है। हालाँकि आप किसी भी name का variable ले सकते हैं।

Python Passing Variables To Constructor

__init__() की help से आप class का object बनाते समय variables pass कर सकते हैं और उन्हें class में use कर सकते हैं।
See Example -

Copy Fullscreen Close Fullscreen Run
class myClass :
  def __init__(self, name) :
    print('Hello : ', name)

myobj = myClass("Rahul Kuamr")
Output
C:\Users\Rahulkumar\Desktop\python>python oop_ex.py
Hello :  Rahul Kuamr

Related Topics :

Rahul Kumar

Rahul Kumar

Hi ! I'm Rahul Kumar Rajput founder of learnhindituts.com. I'm a software developer having more than 4 years of experience. I love to talk about programming as well as writing technical tutorials and blogs that can help to others. I'm here to help you navigate the coding cosmos and turn your ideas into reality, keep coding, keep learning :)

Get connected with me. :) LinkedIn Twitter Instagram Facebook

b2eprogrammers