beginner, idomatic python 2

bambam david at asdf.asdf
Mon Aug 27 00:07:16 EDT 2007


Thank you. I didn't reply earlier because I was trying to get my
head around what you wrote, which was strange and foreign
to me.

It seems to me that the dictionary object you suggested is a
direct replacement for the function code, only more efficient
because the case table is internalised with a hash table, and
the original if/elif/else case table was unlikely to be implemented
as a hash table.

And presumably, it is idiomatic because Python programmers
expect to use dictionaries for their lookup tables.

You have answered a question I didn't know enough to ask :~)
--which is why I started with the general question, so I don't
feel too stupid about that --.

And now I wonder about the 'other' question. Should I consider
dynamically overriding the methods in my 'Device' class, instead
of creating separate classes for the Psp and Pwr devices?
I could create an object of the base Device class, and at init
I could make sure the methods were connected for a Psp or
a Pwr device. When (if ever) is that a good idea?

Steve.




"Dan Bishop" <danb_83 at yahoo.com> wrote in message 
news:1187927388.173203.298660 at e9g2000prf.googlegroups.com...
> On Aug 23, 10:21 pm, "bambam" <da... at asdf.asdf> wrote:
>> Would someone like to suggest a replacement for this? This is a
>> function that returns different kinds of similar objects, depending
>> on what is asked for. PSP and PWR are classes.  I don't really
>> want to re-write the calling code very much: I'm just wondering
>> if the function can be replaced with some kind of OOP pattern.
>>
>> def Device(DeviceType):
>>     if DeviceType=='PSP':
>>         return PSP()
>>     elif DeviceType=="Power Supply"
>>         return PWR()
>>     etc...
>>
>> Thanks!
>
> Typically, you'd use a dictionary:
>
> DEVICE_DICT = {
>    'PSP': PSP.
>    'Power Supply': PWR,
>    # etc.
> }
>
> and your function would simply return DEVICE_DICT[device_type]()
> 





More information about the Python-list mailing list