Home > Net >  Local variable created in __init__ gets compiler error when used outside class definition
Local variable created in __init__ gets compiler error when used outside class definition

Time:10-05

I am writing scripts for JMRI. I have run the following example in JMRI scripting environment that uses Jython2.7. The following code snippet lacks the import statements but I do not think they are relevant. Here goes.

    class MyClass:
         """A Test - MyClass is a test"""
         x=1
         def __init__(self):
             self.y = x
             print 'Initialized'
         def printMe(self):
             print self.y
a = MyClass
print a.x,a.y,a.__doc__

In the above code snippet, I get the following error message:

Caused by: Traceback (most recent call last): File "", line 20, in AttributeError: class MyClass has no attribute 'y'

The last line prints a.x (1) before producing the error message. I have built other objects that have methods that assign Class variables to local variables. I can use them successfully with the instance.attribute form. But in this example, 'Initialized' does not print and y remains undefined.

Any ideas?

CodePudding user response:

a = MyClass

This does not instantiate a new MyClass object, it sets a to the class MyClass. Let's see:

print(a)
# <class '__main__.MyClass'>

Instead you probably wanted:

a = MyClass()
print(a)
# <__main__.MyClass object at 0x107a2af10>

CodePudding user response:

Thank you for helping me. Syntax error that actually compiles is tough on a new Pythonian :)

Working output:

>>> 
... class MyClass:
...      """A Test - MyClass is a test"""
...          x=1
...      def __init__(self,x):
...          self.y = x
...          print 'Initialized'
...      def printMe(self):
...          print self.y
... a = MyClass(MyClass.x)
... print MyClass.x,a.y,a.__doc__
Initialized
1 1 A Test - MyClass is a test
  • Related