[Tutor] declare a variable inside a class
richkappler at gmail.com
Thu Feb 11 16:03:48 EST 2016
Thanks for the reply Martin, and in this instance I cannot post the actual
code (company rules). What I can do is say that with the xslt variable
defined within the formatter method, everything works, but when I pull it
out and put it in the upper level of the class, it gives me a traceback
that says the global variable xslt is not defined. Does that help?
On Thu, Feb 11, 2016 at 3:43 PM, Martin A. Brown <martin at linux-ip.net>
> Hi there again Richard,
> [snipped a bit of stuff]
> >The method that actually formats the messages opens the xslt file,
> >then uses it to format the message. Clever boy that I am, I figured
> >it would be better to open the xslt file once, rather than once per
> >message, so I moved the line
> >xslt = ('path/to/xslt.file')
> Yes, this is a good idea.
> >out of the method it was in and up to the top level of the class, to wit:
> >class MyClass():
> > xslt = ('path/to/xslt.file')
> > def a_bunch-of-methods():
> An impossible method name. That would be a syntax error.
> >and so on.
> >Obviously this didn't work,
> Why is it obvious? What was obvious to me is the syntax error, but
> that does not appear to be what you are asking.
> What was the error message?
> >when the formatting method was called, it through an exception that
> >the variable xslt wasn't defined. This is my first not-a-toy try at
> >OOP, I could use a clue.
> So, before addressing your question, could I gently recommend that
> you post your actual code (clean up any variables or data that you
> don't want the public to see), whether it is running or not, along
> with any error messages (pasted, please).
> This is just a reminder, that this reduces the guesswork on the part
> of the members of the list.
> I think your problem is simply not knowing the name of the variable
> you called 'xslt'. Perhaps the below example helps?
> #! /usr/bin/python3
> class MyClass(object):
> xslt = '/usr/share/nmap/nmap.xsl'
> def find_xslt(self):
> def oh_there_it_is(self):
> def redefine_in_instance(self):
> self.xslt = '/usr/share/sgml/X11/xorg.xsl'
> if __name__ == '__main__':
> # -- instantiate the class
> c = MyClass()
> # -- this is what I think you were doing
> except AttributeError:
> # -- but, try locating the class attribute through self
> # -- class attribute can be overridden in instances....
> # -- newly defined instances will get the default class attribute
> d = MyClass()
> Martin A. Brown
*Java is like Alzheimers; it starts slow and eventually, it takes away all
of your memory.*
More information about the Tutor