how can I create/set a 'file' reference in a attribute of a class

Larry Bates lbates at websafe.com
Mon Feb 26 17:29:04 EST 2007


ken wrote:
> Hi,
> i have a class:
> 
> class LogHandler(ContentHandler):
>     # a reference to a file open by some other function/class
>     outputFile;
> 
> 
>     def endElement(self, name):
>          doSomething(self, "GroupResultList", self.text, outputFile)
> 
> 
> First, I get an error saying 'NameError: global name 'outputFile' is
> not defined' , how can I declare outputFile as a 'file reference'?
> 
> Second , how can I set this file reference after I create the object
> 'LogHandler'?
> 
> How can I do that?
> f = open('dummyFile.txt');
> curHandler = LogHandler()
> curHandler.file = f
> 

Normally this is done when you instantiate the class:

fp = open('dummyFile.txt')
curHandler=LogHander(fp)

class LogHandler(ContentHandler):
    def __init__(self, fp=None):
        self.fp=fp

    def endElement(self, name:
        doSomething(self, "GroupResultList", self.text, self.fp)


but you could set it later if you like:

fp = open('dummyFile.txt')
curHandler=LogHander()
curHandler.fp=fp


-Larry Bates



More information about the Python-list mailing list