From Dict to Classes yes or no and how

Jean-Michel Pichavant jeanmichel at sequans.com
Tue Jun 22 09:08:54 EDT 2010


Jerry Rocteur wrote:
>> -----BEGIN PGP SIGNED MESSAGE-----
>> Hash: SHA1
>>
>> On 06/22/2010 01:32 PM, Jerry Rocteur wrote:
>>     
>>> My input is NOT CSV, I used this format to try and make the question shorter. Although I could create a CSV file,
>>> I'd
>>> like to learn how to code a class to work the way I described in the question.
>>>       
>> Sorry for misunderstanding. Can you maybe give one example that's not
>> CSV? Both your demonstrated files actually are CSV like. Can you be more
>> specific on what actually changes constantly. (Fields given in the
>> files, or the users in the files, or...)
>> Can you tell us, why you want to use classes if the dict approach works
>> great?
>>     
>
> As part of learning Python, I'm also learning OOP! That is why I want to know if this is doable using classes.
>
> The input is not important, I end up with the dictionary as described in the question and as I asked in the question,
> I'd like to access the dictionary as a class and I don't know how or if it is possible.
>
>
> Jerry
>
>   
Dictionary is already a class in python, everything is an object 
actually (even class are objects).

A python OOP approach to your problem would be to subclass the builtin 
'dict' class and override / add the methods.

Here is an example how you can for your User dictionary to accept only 
some types of values.

class User(object):
    def __init__(self, user, secnum, name):
        self.user = user
        self.secnum = secnum
        self.name = name

    def __str__(self):
        return "%(name)s <%(user)s> -- secnum :%(secnum)d" % self.__dict__

    def __repr__(self):
        return self.__str__()

class Users(dict):
    def __init__(self):
        dict.__init__(self) # call the baseclass constructor

    def __setitem__(self, user, value):
        if isinstance(value, User):
            dict.__setitem__(self, user, value)
        else:
            try:
                dict.__setitem__(self, user, User(user, value[0], value[1]))
            except KeyError:
                raise ValueError ("Invalid user format, it shoudl be 
either a User object or a tuple (secnum, name)")
       
users = Users()

users['jro'] = (1325,'john') # the overriden __setitem__ method wil 
ltake care of creating the User object for you.
users['dma'] = User('dma', 654968, 'dominic')

for user in users:
    print users[user]

# Users objects inherit all dict method, values() for instance
for user in users.values():
    print user



For more information: http://docs.python.org/reference/datamodel.html
Read carefully the 3.4.6  section (Emulating container type)


JM



More information about the Python-list mailing list