Search code examples
pythonself

Python error in class


class exampleclass:     
    def meth01(self, name):         
        print self.name

obj1 = exampleclass()
obj1.meth01("James")

error message:

Traceback (most recent call last):   File "<pyshell#5>", line 1, in
<module>
    obj1.meth01("James")   File "<pyshell#3>", line 3, in meth01
    print self.name AttributeError: exampleclass instance has no attribute 'name'

So what have I done wrong to produce this error, the name is in the parameters And I tried to set what name was so that it could print?


Solution

  • You are printing self.name. This is a member variable of the class, not the input variable of the function meth01. In your function name refers to the input, and self.name refers to a member variable of the class. But you are not setting it.

    Do this instead:

    class ExampleClass:
        def meth01(self, name):
            print( name )
    

    To understand what is going on, expand it like this:

    class ExampleClass:
        def setName(self, name):
            self.name = name
        def meth01(self, name):
            print('Input variable name: ', name)
            print('Member variable name: ', self.name)
    
     ec = ExampleClass()
     ec.meth01('John') # This line will fail because ec.name hasn't been set yet.
     ec.setName('Jane')
     ec.meth01('John')
     # This will print:
     #('Input variable name: ', 'John')
     #('Member variable name: ', 'Jane')