2017-05-09 36 views
-3

我的主模塊「actormain」看起來是這樣的:python 3類實例調用彼此的屬性/變量?

import bodymain as bd 
import soulmain as sl 
(import statements of the other relevant modules, long and not super relevant) 

class actor(): 
    def __init__(self, name, pron1, pron2, desc): 
     self.name = name 
     print ('creating ' + self.name + '.') 
     self.owner = self 
     self.pron1 = pron1 
     self.pron2 = pron2 
     self.desc = desc 
     self.body = bd.body(self.owner) 
     self.soul = sl.soul(self.owner) 
     self.greet() 



    def greet(self): 
     print (self.pron1 + ' calls out, "Hey, my name\'s ' + self.name + '."') 

它集「self.body」的值(這是另一個類的一個實例,「身體()」,在另一個模塊),然後以更多細節構建身體的其餘部分(例如:body實例包含在第三個模塊中定義的「hands()」類的實例),將actor實例作爲變量「owner」傳遞。

我的問題:在命令行中,我可以參考,比如說,

actor_instance.body.hands.owner.body.hands.fingers.owner.body... etc.並能正常工作。但是,如果我嘗試從實例中引用(!用完全相同的語法)「的手指,」例如,我得到"AttributeError: 'actor' object has no attribute 'body'."

多,如果在命令行中,我說:

>>>a = actor(args) 

>>>a.body.owner.body 

<bodymain.body object at 0x0000000002F74A90> 

如此清楚的演員對象有一個身體屬性。

但在加載時,這樣的:

>>> import actormain as am 
>>> b = am.actor('bob', 'he', 'his', 'slim') 
creating bob. 
incarnating bob. 
Traceback (most recent call last): 
    File "<pyshell#268>", line 1, in <module> 
    b = am.actor('bob', 'he', 'his', 'slim') 
    File "C:\Program Files (x86)\python361\lib\actormain.py", line 16, in __init__ 
    self.body = bd.body(self.owner, self.bodydesc) 
    File "C:\Program Files (x86)\python361\lib\bodymain.py", line 13, in __init__ 
    self.hand = so.hand(self.owner, '') 
    File "C:\Program Files (x86)\python361\lib\sensorg.py", line 156, in __init__ 
    self.fingers = fingers(self.owner, '') 
    File "C:\Program Files (x86)\python361\lib\sensorg.py", line 110, in __init__ 
    self.a = self.owner.body 
AttributeError: 'actor' object has no attribute 'body' 

這到底是怎麼回事?爲什麼我不能參考這個?

+0

請顯示一個完整的,自包含的示例,演示什麼不起作用。也許'self.owner'不是你認爲它在'finger'類中。 – BrenBarn

+0

,引用fingers.owner給出了actor對象,而fingers.owner.body給出了該actor的body對象。 – ahkent

+0

。 。 。請顯示一個完整的,自包含的示例,演示什麼不起作用。 – BrenBarn

回答

0

你可以從回溯中看到發生了什麼。你的代碼調用self.body = body(...)來創建一個主體。在創建主體的過程中,一些代碼嘗試訪問「所有者」的主體。但業主還沒有身體,因爲它仍在創建過程中。

如果您的身體部位需要能夠訪問身體,則無法從身體創建內部創建它們。直到呼叫body(...)完全結束並返回,身體纔會存在。

+0

非常感謝。我不知道如何閱讀回溯錯誤。 – ahkent