Como implementar property () com nome dinâmico (em python)
Estou programando simulações para neurônios únicos. Portanto, eu tenho que lidar com muitos parâmetros. Agora, a idéia é que eu tenha duas classes, uma para um SingleParameter e uma coleção de parâmetros. Uso property () para acessar o valor do parâmetro com facilidade e tornar o código mais legível. Isso funciona perfeito para um parâmetro sinlge, mas não sei como implementá-lo para a coleção, pois quero nomear a propriedade em Collection após o SingleParameter. Aqui está um exemplo:
class SingleParameter(object):
def __init__(self, name, default_value=0, unit='not specified'):
self.name = name
self.default_value = default_value
self.unit = unit
self.set(default_value)
def get(self):
return self._v
def set(self, value):
self._v = value
v = property(fget=get, fset=set, doc='value of parameter')
par1 = SingleParameter(name='par1', default_value=10, unit='mV')
par2 = SingleParameter(name='par2', default_value=20, unit='mA')
# par1 and par2 I can access perfectly via 'p1.v = ...'
# or get its value with 'p1.v'
class Collection(object):
def __init__(self):
self.dict = {}
def __getitem__(self, name):
return self.dict[name] # get the whole object
# to get the value instead:
# return self.dict[name].v
def add(self, parameter):
self.dict[parameter.name] = parameter
# now comes the part that I don't know how to implement with property():
# It shoule be something like
# self.__dict__[parameter.name] = property(...) ?
col = Collection()
col.add(par1)
col.add(par2)
col['par1'] # gives the whole object
# Now here is what I would like to get:
# col.par1 -> should result like col['par1'].v
# col.par1 = 5 -> should result like col['par1'].v = 5
Outras perguntas que coloquei para entender property ():
Por que atributos gerenciados funcionam apenas para atributos de classe e não, por exemplo, para atributos em python?Como posso atribuir um novo atributo de classe via __dict__ em python?