Python Class For Homogenous Sets Of Objects
Solution 1:
You are look for special methods of classes. Have a look __getattr__
and __getitem__
. You can write your own class. Its instances of this class can have a
, b
and c
as attributes and can do what you describe.
Some thing like this might do part of what you like to do:
classDictCollcetion(object):
def__init__(self, dict_):
self.dict = dict_
def__getattr__(self, name):
return {k: k.name for k in self.dict}
def__getitem__(self, key):
return {k: k.key for k in self.dict}
Solution 2:
I've run into cases where I have manipulated big lists of dictionaries or objects, much like you have. Often those objects are pulled out of a database and populated via an ORM, but I've done it with CSV files as well.
I am not sure that my needs are frequent/common enough that I would look for a module to give me syntactic sugar for it.
Solution 3:
Have you considered just using sets?
my_set = {myclass(...),myclass(...),myclass(...)}
props = {k.prop for k in my_set}
While you could create a class that does that mapping for you, it's not obvious to me that this makes your code any clearer than sticking with standard mapping constructs.
Solution 4:
Following the suggestion of @mike-muller to override the _getattr__
method i created a class here
Post a Comment for "Python Class For Homogenous Sets Of Objects"