我的主模块“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'
这到底是怎么回事?为什么我不能参考这个?
请显示一个完整的,自包含的示例,演示什么不起作用。也许'self.owner'不是你认为它在'finger'类中。 – BrenBarn
,引用fingers.owner给出了actor对象,而fingers.owner.body给出了该actor的body对象。 – ahkent
。 。 。请显示一个完整的,自包含的示例,演示什么不起作用。 – BrenBarn