[Tutor] Creating class / OOP structure
Alan Gauld
alan.gauld at btinternet.com
Wed Nov 6 01:55:06 CET 2013
On 05/11/13 23:55, Johan Martinez wrote:
>
> I need help in modifying my program. Right now it looks as follows:
>
>
> class Filedict():
> def __init__(self, fname):
> self.fname =fname
>
> def parse(self):
> with open(self.fname, 'r') as f:
> ....
> # some file search and parsing logic
> return parsed_file
change this to
self.parsed = parsed_file
>
> def process(self, parsed_object):
remove the parsed_object parameter
> for k in parsed_obj.keys():
replace with
for k in self.parsed.keys():
or more simply
for k in self.parsed:
> return processed_file
And maybe make this
self.processed = processed_file
> f = Filedict('sales.txt')
> parsed_f = f.parse()
> processed_f = f.process(parsed_f)
>
> So I need to pass parsed_f again to the process method. I would like to
> use process method directly on initialized object. For example:
>
> f = Filedict('sales.txt')
> f.process()
my suggestions would lead to
f = Filedict('sales.txt')
f.parse()
f.process()
> Should I store parsed_file as an object attribute as follows?
yes, but you can do it inside parse() which ensures the attribute is
kept updated ifg you call parse a second time and, for any reason,
get a different result.
> class Filedict():
> def __init__(self, fname):
> self.fname =fname
> self.parsed_file = self.parse()
That then becomes
class Filedict():
def __init__(self, fname):
self.fname =fname
self.parse()
And you can remove the parse() line from my 3 liner above...
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list