classes vs dicts

Yermat loic at fejoz.net
Thu May 6 10:33:55 EDT 2004


Holger Türk wrote:
> 
> 
> Isaac To wrote:
> 
>>>>>>> "Charlie" == Charlie  <charlvj at yahoo.com> writes:
>>
>>     Charlie> Greetings, I am pretty new to Python and like it very 
>> much, but
>>     Charlie> there is one thing I can't figure out and I couldn't really
>>     Charlie> find anything in the docs that addresses this.
>>
>>     Charlie> Say I want to write an address book program, what is the 
>> best
>>     Charlie> way to define a person (and the like): create a class (as I
>>     Charlie> would do in Java) or use a dictionary?  I guess using
>>     Charlie> dictionaries is fastest and easiest, but is this 
>> recommended?
>>
>>
>> Python is about making the complexity where it worth.  If you cannot see
>> that a class will help, the safe choice is to do it with a dict.  
>> Later, if
> 
> 
> 
> I don't think so. If you don't want to define set... and get ...
> methods, you can still misuse a class in this way:
> 
> 
> class Person (object): pass
> 
> somePerson = Person ()
> somePerson.name = "his name"
> somePerson.address = "her address"
> 
> 
> instead of
> 
> 
> somePerson = {}
> somePerson ["name"] = "his name"
> somePerson ["address"] = "her address"
> 
> 
> The first alternative is easier to read and even safer:
> If you need to extend the capabilities of the class, you can
> still redefine the behaviour of the data fields using
> descriptors.
> 
> Greetings,
> 
> Holger
> 

And do remember that actually, class ARE (kind of) dictionnary :

 >>> class Person(object): pass
...
 >>> somePerson = Person()
 >>> somePerson.name = "his name"
 >>> somePerson.address = "his address"
 >>>
 >>> somePerson.__dict__
{'name': 'his name', 'address': 'his address'}

So the real question is what do you prefer to type : somePerson.name or 
somePerson["name"] ?

  --
Yermat




More information about the Python-list mailing list