/search.css" rel="stylesheet" type="text/css"/> /search.js">
00001 #!/usr/bin/env python 00002 ''' 00003 Usage 00004 ''' 00005 00006 class ObjectSet(object): 00007 '''Base (abstract) Manager for a colection of certain classes of objects''' 00008 00009 def __init(self): 00010 ''' 00011 Do not call this function in the child class. 00012 This is a boilerPlate for Child class's __init__(). 00013 Intentionally wrong name to avoid reloading __setattr__(). 00014 Child class mush define in its __init__() the following: 00015 - self.classForManaging : a tuple of classes of the managed objects 00016 - self.description : an empty dict for bookkeeping the attributes 00017 ''' 00018 self.classForManaging = (None,) 00019 # description = {name: class} for bookkeeping the attribute 00020 self.description = {} 00021 00022 # --------------------------------------- 00023 def all_dict(self): 00024 '''return the dictionary of name:object of the managed classes''' 00025 return dict((name, self.__dict__[name]) for name in self.description) 00026 00027 # --------------------------------------- 00028 def all(self): 00029 '''return a list of objects of the managed classes''' 00030 return (self.__dict__[name] for name in self.description) 00031 00032 # --------------------------------------- 00033 def __setattr__(self, name, value): 00034 '''hook for caching a name of the Object as the class attribute''' 00035 object.__setattr__(self, name, value) 00036 if isinstance(value, self.classForManaging): 00037 # The attribute class is intentionally only intialized once. 00038 # This way, one can intialize an attribute with a specific class 00039 # but can later use intrisic python type to represent this class 00040 # see the implemetation of class ParameterSet for an example 00041 self.description.setdefault(name, value.__class__) 00042 00043 # # --------------------------------------- 00044 # def __getattr__(self, name): 00045 # '''hook for getting the Object given the attribute''' 00046 00047 # --------------------------------------- 00048 def add(self, name, anObject): 00049 """Add one Object""" 00050 if isinstance(anObject, self.classForManaging): 00051 self.__setattr__(name, anObject) 00052 return anObject 00053 raise AttributeError(str(anObject) 00054 + ' is not a ' 00055 + str(self.classForManaging)) 00056 00057 # --------------------------------------- 00058 def get(self, name): 00059 """Get the Object given the name""" 00060 try: 00061 objName = self.description[name] 00062 except KeyError: 00063 raise AttributeError('Object ' + name + ' is not defined yet') 00064 return self.__dict__[name] 00065