[Tutor] Accessing a list inside a class...

bob gailer bgailer at gmail.com
Thu Apr 9 18:30:49 CEST 2009


With the small font size and lots of blank lines I find this hard to read!

When I look at the optparse documentation I guess you want
print self.opt.inifile

Alexander Daychilde (Gmail) wrote:
>
> I feel like I’m missing something simple, but I have now spent hours 
> googling for an answer. I think I must not be searching for the right 
> terms, or else this is something I’m not supposed to be doing – but it 
> seems straightforward to me…
>
> Here’s my test code (condensed from the actual much longer code I’m 
> adapting from functions to objects – I’m new to OOP, but I’m trying J ):
>
> ___________________________________________
>
> class TestObject:
>
> def __init__(self):
>
> # options and arguments from commandline-->OptionParser
>
> self.opt = ""
>
> self.args = []
>
> def load_cfg(self):
>
> # read+parse commandlnie
>
> self._parse_commandline()
>
> def load_ini(self):
>
> ##### I'm trying to get at 'inifile' from the commandline... #####
>
> print self.opt['inifile']
>
> def _parse_commandline(self):
>
> parser = OptionParser()
>
> parser.add_option("-i", dest = "inifile", help = "specify an ini file 
> to load")
>
> (self.opt, self.args) = parser.parse_args()
>
> if __name__ == '__main__':
>
> # parses command-line argumenmts
>
> from optparse import OptionParser
>
> test = TestObject()
>
> test.load_cfg()
>
> test.load_ini()
>
> ___________________________________________
>
> In the middle is a comment with five hashes to show you the crux of my 
> problem…
>
> If I eliminate “[‘inifile’]”, I can print the list.
>
> How in the world can I get just the ‘inifile’ element?
>
> Ideally, of course, I’m not printing this – I’m going to access it 
> from outside the class, or even inside the class…
>
> The error I get when running the above code:
>
> Traceback (most recent call last):
>
> File "listinclass.py", line 34, in <module>
>
> test.load_ini()
>
> File "listinclass.py", line 17, in load_ini
>
> print self.opt['inifile']
>
> AttributeError: Values instance has no attribute '__getitem__'
>
> I’ve googled for “list in a class” and pretty much every variant I can 
> think of, and I just can’t seem to find a single example of someone 
> trying to get to an element of a list stored in a class… so I 
> apologize for asking a basic/simple question, but I just can’t find it.
>
> Many thanks for your consideration…
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   


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


More information about the Tutor mailing list