2017-08-16 38 views
-2

我在Python初學者所以請原諒我,如果這是微不足道的,但我找不到任何答案爲止。爲什麼我會收到此錯誤訊息?無法訪問與類__init__函數創建的對象:

#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" 

n=5 
class Letters(object): 
    def __init__(self, name, var): 
     self.var=var 
     self.name = name 
    def hello(self): 
     print('my name is %s and my var is %d'%(self.name, self.var)) 
for x in range(0,n): 
    y=chr(x+97).upper()*2 
    y=Letters(y,x+1) 
    y.hello() 
print(BB.var) 

而且我得到這個輸出,這表明已創建的對象,但我不能訪問到BB對象及其變種...

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 

任何解釋?

+1

是。沒有名爲「BB」的變量。一個你'Letter'對象都有'name'屬性被分配到*字符串*'「BB」',但那是不倫不類...... –

+0

的實例有一個'與name'屬性的事實值「BB」不**表示標識符「BB」存在或者是對該實例的引用。我建議閱讀https://nedbatchelder.com/text/names.html – jonrsharpe

+3

我認爲downvotes是過分苛刻。問題本身的質量比典型的第一個問題好得多 - 它提供了一個小型的,自包含的示例,它重現了問題並提供了錯誤消息和堆棧跟蹤。 –

回答

1

您正試圖設置一個全局變量。

globals()["AA"] = Letters("AA", 3) 

所以,你可以這樣做::

for x in range(n): 
    name= chr(x + 97).upper() * 2 
    globals()[name] = Letters(name, x + 1) 

AA.hello() 
print(BB.var) 
+0

這工作,非常感謝。 在'for'循環,我不得不改變以下行,以及以'全局()[名] .hello()' 另外:沒有創建這個全局變量只是意味着它是隨時隨地訪問代碼,或它位於其他地方而不是我正在創建的對象?如果這個問題沒有意義:類對象是否簡單地連接了一組方法和變量而不在類中「定位」 - 只滿足類的形式要求?再次感謝 –

1

兩個問題在這裏:

  1. 每個Letters對象的下一個迭代中消失,您可以使用globals(),像這樣做你的循環。 y是一個新的Letters對象與新namevar - 從之前迭代y已經一去不復返了。如果你想保留你創建的每個對象,你需要使用一個像列表或字典的集合。
  2. 最後,print(BB.var)正在試圖打印名爲BB變量,或者更具體地其var屬性。但是你從來沒有用這個名字創建變量,這就是NameError: name 'BB' is not defined告訴你的。

你可以做這樣的事情,而不是:

l = [] # new empty list 
for x in range(0,n): 
    y=chr(x+97).upper()*2 
    y=Letters(y,x+1) 
    y.hello() 
    l.append(y) # add (append) y to the end of l 
print(l[1].var) # print 2nd item's `var` which is BB 
+0

1)有道理。我有些困惑,因爲我認爲這些對象會被字符串'y'指向,也就是說,在每次迭代時,AA,BB等 - 因此在每次迭代時前一個對象不會消失。 2)這個過程是否等價於Zweedend'globals()[name]'給出的過程,因爲您創建的列表在全局符號表中? –