我在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
任何解釋?
是。沒有名爲「BB」的變量。一個你'Letter'對象都有'name'屬性被分配到*字符串*'「BB」',但那是不倫不類...... –
的實例有一個'與name'屬性的事實值「BB」不**表示標識符「BB」存在或者是對該實例的引用。我建議閱讀https://nedbatchelder.com/text/names.html – jonrsharpe
我認爲downvotes是過分苛刻。問題本身的質量比典型的第一個問題好得多 - 它提供了一個小型的,自包含的示例,它重現了問題並提供了錯誤消息和堆棧跟蹤。 –