London_owl London_owl - 6 months ago 27
Python Question

can't access objects created with class __init__ function :

I'm a beginner in Python so please pardon me if this is trivial, but I couldn't find any answer so far. Why do I get this error message?

#define a class containing a variable and a method
#automatically generate n instances called AA,BB, CC each containing as
#variable the letter's number (a=1, b=2 etc.)
#define a function returning "my name is BB and my var is 2"

class Letters(object):
def __init__(self, name, var):
self.var=var = name
def hello(self):
print('my name is %s and my var is %d'%(, self.var))
for x in range(0,n):

And I get this output, which suggests the objects have been created, yet I can't access to the BB object and its var...

my name is AA and my var is 1
my name is BB and my var is 2
my name is CC and my var is 3
my name is DD and my var is 4
my name is EE and my var is 5
NameError Traceback (most recent call last)
<ipython-input-103-600f444742c0> in <module>()
13 y=Letters(y,x+1)
14 y.hello()
---> 15 print(BB.var)

NameError: name 'BB' is not defined

Any explanation?

Answer Source

Two problems here:

  1. Each of the Letters objects goes away at the next iteration of your loop. y is a new Letters object with new name and var -- the y from prior iterations is gone forever. If you want to keep each object you create you'll need to use a collection like a list or dict.
  2. At the end, print(BB.var) is trying to print a variable called BB, or more specifically its var attribute. But you've never created a variable with that name, which is what NameError: name 'BB' is not defined is telling you.

You could do something like this instead:

l = [] # new empty list
for x in range(0,n):
    l.append(y) # add (append) y to the end of l
print(l[1].var) # print 2nd item's `var` which is BB
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download