Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to implement property() with dynamic name (in python)
    primarykey
    data
    text
    <p>I am programming a simulations for single neurons. Therefore I have to handle a lot of Parameters. Now the Idea is that I have two classes, one for a SingleParameter and a Collection of parameters. I use property() to access the parameter value easy and to make the code more readable. This works perfect for a sinlge parameter but I don't know how to implement it for the collection as I want to name the property in Collection after the SingleParameter. Here an example:</p> <pre><code>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 -&gt; should result like col['par1'].v # col.par1 = 5 -&gt; should result like col['par1'].v = 5 </code></pre> <hr> <p>Other questions that I put to understand property():</p> <ul> <li><a href="https://stackoverflow.com/questions/428264" title="Why do managed attributes just work for class attributes and not for instance attributes in python?">Why do managed attributes just work for class attributes and not for instance attributes in python?</a></li> <li><a href="https://stackoverflow.com/questions/432786/" title="setting class attributes with setattr()">How can I assign a new class attribute via __dict__ in python?</a></li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload