McLawrence
McLawrence

Reputation: 5245

Benefit of using custom initialize function instead of `__init__` in python

I was looking into the following code.

On many occasions the __init__ method is not really used but there is a custom initialize function like in the following example:

def __init__(self):
    pass

def initialize(self, opt):
    # ...

This is then called as:

data_loader = CustomDatasetDataLoader()
# other instance method is called
data_loader.initialize(opt)

I see the problem that variables, that are used in other instance methods, could still be undefined, if one forgets to call this custom initialize function. But what are the benefits of this approach?

Upvotes: 6

Views: 1887

Answers (1)

metatoaster
metatoaster

Reputation: 18898

Some APIs out in the wild (such as inside setuptools) have similar kind of thing and they use it to their advantage. The __init__ call could be used for the low level internal API while public constructors are defined as classmethods for the different ways that one might construct objects. For instance, in pkg_resources.EntryPoint, the way to create instances of this class is to make use of the parse classmethod. A similar way can be followed if a custom initialization is desired

class CustomDatasetDataLoader(object):

    @classmethod 
    def create(cls):
        """standard creation""" 
        return cls() 

    @classmethod
    def create_with_initialization(cls, opt):
        """create with special options."""
        inst = cls()
        # assign things from opt to cls, like
        # inst.some_update_method(opt.something) 
        # inst.attr = opt.some_attr
        return inst 

This way users of the class will not need two lines of code to do what a single line could do, they can just simply call CustomDatasetDataLoader.create_with_initialization(some_obj) if that is what they want, or call the other classmethod to construct an instance of this class.

Edit: I see, you had an example linked (wish underlining links didn't go out of fashion) - that particular usage and implementation I feel is a poor way, when a classmethod (or just rely on the standard __init__) would be sufficient.

However, if that initialize function were to be an interface with some other system that receives an object of a particular type to invoke some method with it (e.g. something akin to the visitor pattern) it might make sense, but as it is it really doesn't.

Upvotes: 4

Related Questions