Saturday, 17 August 2013

Python object oriented design concepts

Python object oriented design concepts

I'm just getting back to programming after a 20 year gap. I thought Python
looked fairly straightforward and powerful, so I have done an online
course and some reading.
I'm now looking at some simple projects to get familiar with the language.
One of the challenges is getting my head around object oriented
programming, which was not around when I last wrote a program.
My first project was to read in a data file containing information about a
share portfolio, do some calculations on each and print a report. I have
this working.
So now I am looking at something more advanced, reading in the data and
storing it, then using the data to provide answers to interactive
questions. My question is how to store the data so it can be accessed
easily.
My first thought was to make a list of lists, eg,
companies = [ ['AMP', 1000, 2.50], ['ANZ', 2000, 17.00], ['BHP', 500,
54.30] ]
This can be accessed in loops easily enough, but the access methods are
not exactly friendly - numbers as indexes instead of names:
companyqty = companies[1][1]
Or for loops:
for company in companies:
if company[0] == 'BHP':
companyqty = company[1]
Then I thought about a dictionary, with the value being a list:
companies = {'AMP':[1000, 2.50], 'ANZ':[2000, 17.00], 'BHP':[500, 54.30] }
companyqty = companies['BHP'][0]
This provides immediate access to any given company, but is still stuck
with the numeric indexes.
So I am wondering how to structure this in an object oriented manner so as
to be able to hold a list of companies and all the associated data, and be
able to access the values conveniently. All my ideas so far just look like
lists or dictionaries as above.
Or is this sort of problem not really suited to an object oriented approach?
Thanks

No comments:

Post a Comment