python3类实例调用彼此的属性/变量?

2024-09-30 06:15:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我的主要模块“actormain”如下所示:

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(),”的实例),然后逐步构建主体的其余部分(例如:body实例包含第三个模块中定义的“hands()”类的实例),并将actor实例作为变量“owner”传递

我的问题是:在命令行中,我可以引用

actor_instance.body.hands.owner.body.hands.fingers.owner.body... etc.而且效果很好。但是如果我尝试引用它(使用相同的语法!)例如,在实例“fingers”中,我得到"AttributeError: 'actor' object has no attribute 'body'."

更多,如果在命令行中,我说:

>>>a = actor(args)

>>>a.body.owner.body

<bodymain.body object at 0x0000000002F74A90>

很明显,actor对象有一个body属性

但在装载时:

>>> 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'

到底怎么回事?为什么我不能引用这个


Tags: 实例nameinimportselfinitlinebody
1条回答
网友
1楼 · 发布于 2024-09-30 06:15:38

你可以从回溯中看到发生了什么。您的代码调用self.body = body(...)来创建主体。在创建主体的过程中,一些代码试图访问“所有者”主体。但它的主人还没有尸体,因为它还在被创造的过程中

如果您的身体部位需要能够访问身体,则不能从身体创建内部创建它们。直到对body(...)的调用完全完成并返回,主体才会存在

相关问题 更多 >

    热门问题