[Tutor] learning classes (kinda long)

Kent Johnson kent37 at tds.net
Sun Jul 31 16:26:23 CEST 2005


Reed L. O'Brien wrote:
> This is a little long
> a program consisting of
> bsserver.py ## to define server class and methods
> bscaller.py     ## to define a test class subclasses for services (imap
> http pop dns et al)
> bslogger.py ## to log and analyze tests and send emails on
> exceptions/failures
> bsmain.py  ## that instantiates classes and controls flow
> bs.conf  ## the config
> given a configuration:
> 
> [foo]
> 
> fqdn: foo.dom.com
> services: http,imap,pop
> 
> [bar]
> 
> fqdn: bar.dom.org
> services: dns,http
> 
> then given:
> 
> config = ConfigParser.ConfigParser()
> config.read('config.txt')
> 
> I want to be able to create instances of a class, via a loop; feeding in
> the values from the config. something like:
> 
> for section in config.sections():
>     section = bsserver.Server() 
> 

As Luke and Alan have pointed out, you are probably better off storing the servers in a map. So the above would look like

sections = {}
for section in config.sections():
    sections[section] = bsserver.Server() 


> Additionanlly I would like to call them and pass in their name from teh
> section part of the config and also the options fqdn as well as services
> as a list.
> 
> for section in config.sections():
>     section = bsserver.Server(config.get(section, 'fqdn'),
> config.get(section, 'services')
> 
> currently my server class is defined as:
> 
> class Server:
>     def fqdn(self, value):
>         self.fqdn
>     def services(self, value):
>         self.services = value
>     def name(self, value):
>         self.name = value

If you want to pass arguments to the Server constructor you need to define an __init__() method. You want to pass two arguments - section and fqdn - so your __init__() method will look like this:
  def __init__(self, section, fqdn):
    self.section = section
    self.fqdn = fqdn


Note that setter methods like fqdn(), services(), name() are rarely used in Python. Common practice is to access the attributes directly even from client code.

Kent



More information about the Tutor mailing list