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

K

ken

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
 
L

Larry Bates

ken said:
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
 
B

Bjoern Schliessmann

ken said:
Hi,
i have a class:

class LogHandler(ContentHandler):
# a reference to a file open by some other function/class
outputFile;

What do you intend to achieve with this last line, and what's
the ';' for?
First, I get an error saying 'NameError: global name 'outputFile'
is not defined' , how can I declare outputFile as a 'file
reference'?

If I'm not mistaken it would be best to read the Python tutorial.
Second , how can I set this file reference after I create the
object 'LogHandler'?

You shouldn't create an object that has the same name as its class.

Anyway, you can open a file using

var = file("/path/to/file")
How can I do that?
f = open('dummyFile.txt');
curHandler = LogHandler()
curHandler.file = f

Is it this you want to do?

class LogHandler(ContentHandler):
pass

f = file("dummyfile.txt")
curHandler = LogHandler()
curHandler.file = f

Seems quite pointless to me.

I'm still confused about your intentions.

Regards,


Björn
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,436
Messages
2,571,696
Members
48,796
Latest member
Greg L.
Top