Python Forum

Full Version: Mask superclass __init__
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Is there anyway to hide the superclass initialization from the user?

For example:
class BaseClass:
    def __init__(self):
        self.param = 10

class OtherClass(BaseClass):
    # I don't want the OtherClass to explicit call the baseclass initialization like this
    def __init__(self):
        super().__init__()
Why do you want to hide it? It is very difficult to hide anything in python code.

Would a metaclass suit your needs?
class AutoSuperInitialized(type):
    def __new__(meta, name, superclasses, memberdict):
        i = '__init__'
        if i in memberdict:
            f = memberdict[i]
            def __init__(self, *args, **kwargs):
                super(cls, self).__init__(*args, **kwargs)
                f(self, *args, **kwargs)
            memberdict[i] = __init__
        cls = type.__new__(meta, name, superclasses, memberdict)
        return cls
    
    
class BaseClass(metaclass=AutoSuperInitialized):
    def __init__(self):
        print('BaseClass __init__ called!')
        
class OtherClass(BaseClass):
    def __init__(self):
        print('OtherClass __init__ called!')
        
if __name__ == '__main__':
    obj = OtherClass()
Exclamation it works even with sub-sub-classes!
Quote:Why do you want to hide it? It is very difficult to hide anything in python code.

I think it becomes more simple and clean to the framework user to not directly call superclass init .

Quote:Would a metaclass suit your needs?

Great! I saw something familiar in Django code.
The django.db.Model does not need to be initialized since it uses a metaclass to initialize its properties.
(Jan-10-2018, 09:36 PM)fig0 Wrote: [ -> ]I think it becomes more simple and clean to the framework user to not directly call superclass init .
The drawback of this is that you cannot fine tune the constructor's parameters. Simplicity has a cost...
Can't I simple use the class __new__ magic method instead of creating a metaclass?
(Jan-11-2018, 05:45 PM)fig0 Wrote: [ -> ]Can't I simple use the class __new__ magic method instead of creating a metaclass?
I don't think so. There is nothing magic in the __new__() method. Its role is to create a raw object prior to intialization. I wouldn't try to use __new__() to avoid calling the ancestor classes' constructor. It is not good design, and it will be difficult to handle several levels of inheritance.

Python provides metaclasses as the normal way to handle such specific type requests. What do you think is wrong with using a metaclass?