0

I have a dictionary in some class,

self.tables={'tableA':df_a,'tableB':df_b,...,'tableZ':df_z}

and a corresponding list of indices for each dataframe:

self.indices={'tableA':indices_a,'tableB':indices_b,...,'tableZ':indices_z}

The idea is that when the user of my class writes

someClass.tableA 

he will get

self.tables['tableA'].iloc(self.indices['tableA'])

and when he will set it eg

someClass.tableA=some_df

He will actually change the corresponding indices.

I know how to do this with 26(26 comes from the a-z portion) @property and other 26 @property.setter,for instance:

@propery
def tableA(self):
    return self.tables['tableA'].iloc[self.indices['tableA']]

Is there a better way?

yoni keren
  • 300
  • 2
  • 14
  • You probably want to use a `__getattr__` hook here; `def __getattr__(self, name): if name in self.tables: return self.tables[name].iloc[self.indices[name]]` (and `raise AttributeError` if the name is not a valid table). – Martijn Pieters Jun 23 '19 at 10:39
  • Thx,I suppose I'll need to use __setattr__ in the same manner (although it's invoked even if the attr does exist as opposed to __getattr__) – yoni keren Jun 23 '19 at 11:55
  • If `someInstance.tableA = ...` must work, then yes, implement `__setattr__` and call `super().__setattr__()` for anything that isn't a table name. Be careful with accessing attributes on `self` that have not yet been set, or access `self.__dict__` keys to avoid triggering further attribute lookups. – Martijn Pieters Jun 23 '19 at 12:38

0 Answers0