Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #55512

Re: Class or Dictionary?

Date 2011-02-11 21:01 +0100
From Jean-Michel Pichavant <jeanmichel@sequans.com>
Subject Re: Class or Dictionary?
References <abfa0bc0-29d4-4e52-a7f8-867f9760c72a@s11g2000prs.googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.114.1297454525.1633.python-list@python.org> (permalink)

Show all headers | View raw


Martin De Kauwe wrote:
> Hi,
>
> I have a series of parameter values which i need to pass throughout my
> code (>100), in C I would use a structure for example. However in
> python it is not clear to me if it would be better to use a dictionary
> or build a class object? Personally I think accessing the values is
> neater (visually) with an object rather than a dictionary, e.g.
>
> x = params['price_of_cats'] * params['price_of_elephants']
>
> vs.
>
> x = params.price_of_cats * params.price_of_elephants
>
> So currently I am building a series of class objects to hold different
> parameters and then passing these through my code, e.g.
>
> class EmptyObject:
>     pass
>
> self.animal_prices = EmptyObject()
> self.price_of_cats = 12 or reading a file and populating the object
>
>
> I would be keen to hear any reasons why this is a bad approach (if it
> is, I haven't managed to work this out)? Or perhaps there is a better
> one?
>
> thanks
>
> Martin
>   
Using classes is the best choice.

However, if because there would be too much classes to define so that 
you are forced to use your EmptyObject trick, adding attributes to the 
inntance dynamically, I'd say that dictionnaries are a more common pattern.

Ideally, you would have something like:

class PriceHolder(object):
    @classmethod
    def fromFile(cls, filename):
       # example of abstract method
       pass

class Animals(PriceHolder):
    def __init__(self):
       self.cat = None
       self.elephant = None

class Fruits(PriceHolder):
    def __init__(self):
       self.banana = None
       self.apple = None


Then you would have to write 100 PriceHolder subclasses...

JM

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Re: Class or Dictionary? Jean-Michel Pichavant <jeanmichel@sequans.com> - 2011-02-11 21:01 +0100
  Re: Class or Dictionary? Martin De Kauwe <mdekauwe@gmail.com> - 2011-02-11 15:45 -0800
    Re: Class or Dictionary? Martin De Kauwe <mdekauwe@gmail.com> - 2011-02-12 01:20 -0800
    Re: Class or Dictionary? Martin De Kauwe <mdekauwe@gmail.com> - 2011-02-11 16:24 -0800
    Re: Class or Dictionary? Martin De Kauwe <mdekauwe@gmail.com> - 2011-02-12 01:06 -0800

csiph-web