Confusion About Classes

Steven Bethard steven.bethard at gmail.com
Mon Dec 27 20:00:12 EST 2004


flamesrock wrote:
> Hi,
> 
> I've been playing like mad with all sorts of python modules..but I
> still can't seem to get my head around the proper use of a class and
> self. The question stems from this code I made(snippet):
[snip misaligned code]

When posting to c.l.py it's greatly appreciated if you use spaces 
instead of tabs in your code.  Many newsreaders strip out tabs.

> The goal is to create a create_server object with the given parameters,
> and then call the method createUniversalConfig() without passing and
> parameters to it.


Sounds like you want to write:

     def createUniversalConfig(self):
         ''''''
         self.parser.add_section('score')
         self.parser.set('score', 'domain', self.score_domain)
         self.parser.set('score', 'server', self.score_servername)
         self.parser.set('score', 'server', self.score_port)

Then you can do something like:

cs = create_server(... appropriate arguments ...)
cs.createUniversalConfig()

However, this will only work if somewhere previously (probably 
__init__), you wrote assignment statements like:

         self.score_domain = ...
         self.score_servername = ...
         self.score_port = ...

Looking at your code, I don't see that you've done this anywhere.  Where 
should score_domain, score_servername and score_port be coming from? 
Are they the same as the 'domain', 'servername' and 'httpport' 
parameters to __init__?  If so, you should write your code like:

     def createUniversalConfig(self):
         ''''''
         self.parser.add_section('score')
         self.parser.set('score', 'domain', self.domain)
         self.parser.set('score', 'server', self.servername)
         self.parser.set('score', 'server', self.__httpport)

As an aside, there's probably no need to prefix your variables with 
double-underscores -- this causes name mangling that's generally not 
necessary in a "we're all consenting adults" language like Python.

Steve



More information about the Python-list mailing list