# [Tutor] Structuring a class

bob gailer bgailer at gmail.com
Tue Jun 15 05:13:00 CEST 2010

```On 6/14/2010 8:08 PM, Lang Hurst wrote:
> I'm trying to figure out how to deal with data which will look
> something like:
>
>    Student:Bob Hurley
>    ID: 123456
>    Period:4
>    Credits:
>       Algebra C (20P)
>             Chapter 1
>                  Date: September 14, 2010
>                  Credits:1.5
>                  Notes: Probably cheated on final.  Really watch on
> next quiz/test.
>             Chapter 2
>                  Date: October 31, 2010
>                  .
>                  .   **and so on**
>                  .
>       Consumer Math (24G)
>             Module 2
>                  .
>                  .
>
Before deciding on data structures I suggest you give the big picture.
Where will data come from? What do you plan to do with it?

Often a case like this is better handled using a relational database.
Python happens to come with the sqlite3 module which makes database work
quite easy.

>
> So, I just figured that I would have a couple of nested dictionaries.
>
>    bob = Student('123456','Bob Hurley')
>    bob.period = 4
>    bob.grad_class = 2010
>    bob['credits']['Algebra C (20P)']={'Chapter 1':{'Date':'September
> 12, 2010', 'Grade':'87', **and so on**}}
>
> This works, for the most part, from the command line.  So I decided to
> set up a class and see if I could work it from that standpoint (I'm
> doing this to scratch an itch, and try to learn).  My preliminary
> class looks like:
>
>    class Student:
>        def __init__(self, ident=' ', name=' ', period=' ',
> grad_class=' ', subject=' ', notes=' ', credit=' '):
>            self.name = name
>            self.ident = ident
>            self.period = period
>            self.notes = notes
>     #      self.credit = {{}} <--- BAD
>            self.credit = {}
>
> I'm sure that someone will enlighten me as to where my poor coding
> skills are especially weak.  It's the last line there (self.credit...)
> which I can't figure out.  The credits may be in any of about 30
> different subjects (teaching at a continuation high school makes for
> interesting times).

You should define a class for Credit, which will hold the credit
attributes, just like you did for Student. Then assign instances of
Credit to entries in self.credit.
>
> If I don't set it to anything, ie, like it is, I get an error
>
>    Stud instance has no attribute '__getitem__'
>
> If I try to leave it available for adding to somewhat dynamically, I
> get a 'wtf' from python.

Sorry I don't understand these. It is a good idea to post full
tracebacks and the code that raises the exception.

--
Bob Gailer
919-636-4239
Chapel Hill NC

```