Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing many objects in an elegant way

I'm looking for a elegant way to initialize many objects.

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

Currently, I'm doing it like this:

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()

and.. well, it doesn't looks good.

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.

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

like image 875
Dzawor Avatar asked Feb 01 '26 18:02

Dzawor


1 Answers

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

Instead, you could create an auxiliary, helper, function that takes self and setattr on it. An example of this with a couple of objects from collections would look like this:

from collections import UserString, deque, UserDict

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

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 :-).

Now your sample class can just call construct() with the defaults in __init__ and be done with:

class Foo:
    def __init__(self):
        construct(self)

the construct function could of course be defined in Utils as required or, as a method in the class.

like image 186
Dimitris Fasarakis Hilliard Avatar answered Feb 04 '26 08:02

Dimitris Fasarakis Hilliard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!