1

I'm trying to design a "Time Tracker" device. I want to be able to define a class line like:

class line():
 def __init__(self, course, weekHours, hoursTotal, comment)
 self.course = course
 self.weekHours = weekHours
 self.hoursTotal = hoursTotal
 self.comment = comment

Then be able store an array (I guess it's called a list in Python?), of these class objects. So I can print a table produced by all of these lines and save these lines to an output file and then later be able to read that back into this list to view the table or make changes. do I declare table = [class line()]? If so, how do I access each of these objects in the list? I want to be able to differentiate them so I can edit a particular "line" if necessary.

asked Nov 6, 2013 at 6:18
2
  • You can do it like with any other object in python... you don't need to declare anything. Commented Nov 6, 2013 at 6:21
  • @sashkello Sorry I've been working in C for too long now that I forget how Python works exactly. Commented Nov 6, 2013 at 6:26

1 Answer 1

2

You can store class instances in a list:

lines = []
lines.append(line('Math', '3', '12', 'Hello World!'))
...

To get the i'th line, you'd just do:

lines[i]

Note that there really isn't a good reason to have a class here. a python dict would be more efficient:

lines = []
lines.append({'course': 'Math', ...})
answered Nov 6, 2013 at 6:21
Sign up to request clarification or add additional context in comments.

7 Comments

I was thinking I couldn't use a dict but now I see how it'd work and I could make the course name the key and then I could eliminate that from my class line(). Thanks!
How would you access the member variables of class Lines()? lines[i].course seems not to work.
@holzkohlengrill -- That should work. What error are you seeing?
@mgilson Indeed, you are right. What was confusing me is that in my case it appends the data during runtime (from a file). What I find very inconvenient is that the IDE (PyCharm) is not proposing (probably because it don't know any list entries at this point) any classes member variables. Is there a way to get over this? The list will only contain entries of the same type/class.
@holzkohlengrill -- Unfortunately, I don't know anything about how PyCharm does it's type inferencing... :-/
|

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.