简体   繁体   中英

Every Class in Django must have the function __init__()?

I am learning Django and understand that the __init__() function is used to construct object from certain class. However,I also see some class code without a __init__() class function, so my question is that is the __init__() function really necessary for all class? And you might also correct me if there is anything wrong with my understanding of this function. Thank you.

Check out the documentation on Class objects

The __init__() function is called when the object is created:

>>> class MyBoringClass(object):
    def __init__(self):
        print 'Being initialised!'

>>> b = MyBoringClass()
Being initialised!

It can also accept parameters:

>>> class MyInterestingClass(object):
    def __init__(self, name):
        print 'Initialised as {}'.format(name)
        self.name = name

>>> i = MyInterestingClass('Mona')
Initialised as Mona
>>> i.name 
Mona

If you don't need it, then don't use it.

By the way, Django is a web framework written in Python - __init()__ comes from Python.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM