The advantage of using a custom initialization function instead of `__init__` in python

I studied the following code .

In many cases, the method __init__is not actually used, but there is a user-defined function initialize, as in the following example:

def __init__(self):
    pass

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

Then it is called:

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

I see a problem that the variables that are used in other instance methods can still be undefined if you forget to call this user-defined function initialize. But what are the benefits of this approach?

+6
source share
1 answer

API- (, setuptools) , . __init__ API , . , pkg_resources.EntryPoint - parse. ,

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 

, , CustomDatasetDataLoader.create_with_initialization(some_obj), , , - .

: , , ( ). , , , classmethod ( __init__) .

, - , (, - ), , .

+2

All Articles