Initializing many objects in an elegant way
<p>I'm looking for a elegant way to initialize many objects.</p>

<p>Let's say that I have a <code>Utils</code> module, which has an interface to SVN, Git, Make and other stuff.</p>

<p>Currently, I'm doing it like this:</p>

<pre><code>from Utils.Config import Config, Properties
from Utils.Utils import PrettyPrint, SVN, Make, Bash, Git

class Build(object):

    def __init__(self):
        self.config = Config()
        self.make = Make()
        self.env = Properties()
        self.svn = SVN()
        self.git = Git()
        self.bash = Bash()
        self.pretty_print = PrettyPrint()
</code></pre>

<p>and.. well, it doesn't looks good. </p>

<p>Is there any way to do this in more elegant way? I suppose that it can be a design problem, but I have no idea how to solve this.</p>

<p>I was thinking about creation <code>Base class</code> which will init all of these classes inside the <code>Utils</code> module. What do you think?</p>

<p>I wouldn't create a class and place it as a base, <em>that seems like overkill, too bulky of an approach</em>.</p>

<p>Instead, you could create an auxiliary, helper, function that takes <code>self</code> and <code>setattr</code> on it. An example of this with a couple of objects from <a href="https://docs.python.org/3/library/collections.html" rel="nofollow"><code>collections</code></a> would look like this:</p>

<pre><code>from collections import UserString, deque, UserDict

def construct(instance, classes = (UserString, deque, UserDict)):
    for c in classes:
        setattr(instance, c.__name__.lower(), c([]))
</code></pre>

<p>Your case also fits nicely since your objects don't have some initial value required, so you can generalize and treat them in the same way :-).</p>

<p>Now your sample class can just call <code>construct()</code> with the defaults in <code>__init__</code> and be done with:</p>

<pre><code>class Foo:
    def __init__(self):
        construct(self)
</code></pre>

<p>the <code>construct</code> function could of course be defined in <code>Utils</code> as required or, as a method in the class. </p>

python python-3.x