[Tutor] declare a variable inside a class

Mark Lawrence breamoreboy at yahoo.co.uk
Thu Feb 11 15:54:08 EST 2016


On 11/02/2016 20:28, richard kappler wrote:
> Trying to optimize the modular input we wrote for Splunk, the basic
> structure (dictated by Splunk) is the entire script is a class with
> numerous methods within. The modular input reads a tcp stream, starts a new
> thread for each source, reads the messages from that source into a buffer,
> checks for stx and etx, formats it using an xslt and sends the result out
> to splunk.
>
> 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')
>
> 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():
>
> and so on.
>
> Obviously this didn't work, 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.
>
> regards, Richard
>

I'd be inclined to put "xslt = ('path/to/xslt.file')" right back where 
it started, otherwise every instance of Myclass is limited to whatever 
that path is.

If you insist on keeping xslt at the class level, then you need 
something like:-

myclass = MyClass()
myclass.xslt ...

or:-

def aMethod(self):
     self.xslt ...

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence



More information about the Tutor mailing list