2
\$\begingroup\$

I am writing web application using flask framework + mongodb. I have an issue, should I use classes for my mongo entities or just use dictionaries for them.

class School:
    def __init__(self, num, addr, s_type):
        self.num = num
        self.addr = addr
        self.s_type = s_type

or just create dictionary for any entity like:

school = { "number" : request['number'] ,
           "address": request['address'],
           "type"   : request['type'] }
\$\endgroup\$
2
\$\begingroup\$

I'm not familiar with that framework, but if there is more than one school and you are going to use Python to access those values (such as the school's address), I'd use a class. Think of it this way: Classes are usually meant to be instantiated, or at least to be a group of functions for a specific purpose.

Instead of creating a dict for each school you simply instantiate the class:

MIT=School(1,'Cambridge','university')
Harvard=School(2,'Cambridge','university')
>>> MIT.address
'Cambridge'
>>> Harvard.s_type
'university'

Or whatever pattern you are using.

This way you can also add functions to it:

class School:
    def __init__(self, name, num, addr, s_type):
        self.num = num
        self.name = name
        self.addr = addr
        self.s_type = s_type
    def describe(self):
        print "%s is a %s located at %s." % (self.name, self.s_type, self.address)
    def request(self,arg):
        request[arg] # I'm not sure if that's what you want, I copied it from the dict you had there

>>> MIT.describe()
MIT is a university located at Cambridge.
>>> MIT.request('name')
# Whatever that thing does
\$\endgroup\$
1
  • 1
    \$\begingroup\$ I understand your point. Also I can perform some functions like def asDictionary(): or def save(): to save it in mongo or than write function for saving in SQL database. Thank you :D \$\endgroup\$ – Valery Jun 6 '13 at 21:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.