[Tutor] declare a variable inside a class

Martin A. Brown martin at linux-ip.net
Thu Feb 11 15:43:57 EST 2016

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

More information about the Tutor mailing list