[Tutor] declare a variable inside a class
alan.gauld at btinternet.com
Thu Feb 11 17:05:16 EST 2016
On 11/02/16 21:20, Peter Otten wrote:
>> 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?
> You need to qualify the class attribute with self to access it from within a
Or you could use the class name since it is a class attribute:
>>>> class MyClass:
> ... xslt = "/path/to/file"
> ... def some_method(self):
> ... print(MyClass.xslt)
If you need the possibility of having different paths for
different instances you need to initialise it in
an __init__() method:
self.xslt = path
instance1 = MyClass('/some/path/here')
instance2 = MyClass('/another/path/here')
The way you have it currently both instances share the same path.
But that may be what you want.
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:
More information about the Tutor