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?
4 Answers 4
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')
3 Comments
name and self.name are two completely different things! def meth01(self, not_a_name): self.name = not_a_nameYou need to make your __init__ method
class exampleclass:
def __init__(self, name):
self.name = name
Comments
A variable name is part of the parameter list, but there's no name member value in the example class object itself (yet).
Think of what your code does, step by step. First it instantiates a new exampleclass object.
You then call obj1.meth01("James"). meth01 is passed with the values self = obj1 and name="James"
meth01 then tries to find a value stored as obj1.name, but none exists, since in this case name is local to the method meth01 and is not part of the object obj01 itself.
Comments
You need to make a constructor that is used to initialise an object.
Make your __init__ method like this.
class exampleclass:
def __init__(self, name):
self.name = name
NOTE: Declare the constructor as mentioned only.
You can understand self like this:
Self stores the address of the object from which the constructor or method is called.
So self.name=name would result in assigning the data member of the object from which it is called to the variable name which is passed as parameter to the constructor.
self.name.