1

I need a construction like:

mainclass["identificator 1"].categories["identificator 2"].plots["another string"].x_values

I write this with many classes like:

class c_mainclass(object):

    def __init__(self):
        self.categories={}
        self.categories["identificator 2"]=c_categories()

class c_categories(object):

    def __init__(self):
        self.plots={}
        self.plots["another string"]=c_plots()

class c_plots(object):

    def __init__(self):
        self.x_values=[2,3,45,6]
        self.y_values=[5,7,8,4]

mainclass={}

mainclass["identificator 1"]=c_mainclass()
#mainclass["identificator bla"]=c_mainclass(bla etc)

print(mainclass["identificator 1"].categories["identificator 2"].plots["another string"].x_values)

I'd like to define that all as "subattributes" within only one class like:

class c_mainclass={}:

    setattr(mainclass["identificator 1"],"categories",{})
    ...etc.

What's the most practical way to do this?

Caniko
  • 867
  • 2
  • 11
  • 28

1 Answers1

0

You could do something akin to Autovivification check this SO post out.

(this is pasted from the answer to the linked SO question.)

class AutoVivification(dict):
    """Implementation of perl's autovivification feature."""
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value

a = AutoVivification()

a[1][2][3] = 4
a[1][3][3] = 5
a[1][2]['test'] = 6

print a

{1: {2: {'test': 6, 3: 4}, 3: {3: 5}}}
Community
  • 1
  • 1
srj
  • 9,591
  • 2
  • 23
  • 27