Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to prevent init from being called?

I'm editing the original question because we're all focusing on SHOULD you ever want to do this. My question is simply CAN I do this and HOW (understanding that there may be several solutions). So I'm just going to leave the actual question and cut out the background.

Suppose I have a base class and a child class. Is there anything I can do in the base class to prevent __init__ from being called on the child class - or at least throw an exception or even log if __init__ exists or is called on the child class? I do want the __init__ method to be called on the parent class.

Edit/Conclusion - After exploring the options presented in the answers, I decided that doing this would be bad style. I will solve my problem a different way. Nonetheless, hopefully the answers below are helpful in case someone else wants to do this.

like image 313
Matthew Lund Avatar asked Feb 08 '12 03:02

Matthew Lund


People also ask

Is INIT called automatically?

Note: The __init__() function is called automatically every time the class is being used to create a new object.

Does init always take self?

The first argument in our __init__ method will always be self (just like pretty much every other method). After that we need to declare any arguments we want our class to accept. The main thing you'll pretty much always see in a __init__ method, is assigning to attributes.

Is INIT called once?

Init functions are called only once, after all the variable declarations and before the main function. It allows you to initialize whatever your program needs before running.

Does init call New in Python?

Whenever a class is instantiated __new__ and __init__ methods are called. __new__ method will be called when an object is created and __init__ method will be called to initialize the object.


1 Answers

Most of these answers are outdated.

This can be easily done since python 3.6. It was defined in PEP487.

class Base:
    def __init_subclass__(cls):
        if Base.__init__ is not cls.__init__:
            raise Exception(f'Do not override {cls}.__init__')

class Good(Base):
    pass

class Bad(Base):
    def __init__(self):
        pass

Good() # No problem
Bad()  # Raises Exception
like image 104
TKK Avatar answered Sep 21 '22 17:09

TKK