still struggling, howto use a list-element as a name ?

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sat Jan 6 17:16:26 EST 2007


Stef Mientki a écrit :
> In the example below, "pin" is an object with a number of properties.
> Now I want
> 1- an easy way to create objects that contains a number of these "pin"
> 2- an multiple way to access these "pin", i.e.
>         device.pin[some_index]
>     device.some_logical_name
> ad 1:
> a dictionary (as "pinlist" in the example) seems a very convenient     
> way (from a viewpoint of the device creator).
> As you can see in the "__init__" section this dictionary can easily be 
> transported to the pin-objects.
> 
> ad 2:
> THAT's the problem: how do automate these lines "self.GND = self.pin[0]"
> 
> I'm also in for other solutions.

I'm afraid I don't understand your design (nor the domain FWIW). A few 
comments anyway:

> 
> class Power_Supply(device):

Please reread my comments about naming convention in a previous thread...

>     pinlist = {

This is *not* a list, so naming it 'pinlist' is misleading. Also, why is 
this defined here ?

>         0: ('GND', _DIG_OUT, _par2),
>         1: ('VCC', _DIG_OUT, _par33)
>         }
> 
>     def __init__(self):
>         # store pin-names and pin-parameters in pins
>         for k in self.pinlist.keys():
>           self.pin[k].Name = self.pinlist[k][0]

What is 'self.pin' ? Where is it defined ? (NB : please try to post 
*runnable* code).

And FWIW, if it's a container, why is it named 'pin', and not 'pins' ?


>           self.pin[k].Value = self.pinlist[k][2]

The appropriate way to use the for loop here is:
           for k, v in self.pinlist.items():
              self.pin[k].name = v[0]
              # etc

>         # for some pins, we also want to be able to use logical names
>         # HOW TO USE SOMETHING like
>         #     "self.pinlist[0] = self.pin[0]"
>         # INSTEAD OF
>         self.GND = self.pin[0]
>         self.VCC = self.pin[1]

you can build a 'reversed index':
         # store pin-names and pin-parameters in pins
           for k, v in self.pinlist.items():
              self.pin[k].name = v[0]
              self.pin[k].value = v[2]
              self.reversed_index[v[0]] = self.pin[k]

and then use the __getattr__ hook:

   def __getattr__(self, name):
     return self.reversed_index[name]

But the whole thing still looks awfully convulted and kludgy to me, and 
I suspect serious design flaws... Why don't you try and explain  your 
real problem, instead of asking how to implement what you *think* is the 
solution ?



More information about the Python-list mailing list