【问题标题】:Why does my object disappear?为什么我的对象消失了?
【发布时间】:2012-06-26 16:11:30
【问题描述】:

我创建的对象有问题,然后在函数中使用。

class environnement:
    def __init__(self, n, dic={}, listr=[], listf=[]):
        self.taille=n
        self.reg=dict(dic)
        self.raccess=listr
        self.faccess=listf

首先我在我的函数compilProgram 中创建一个环境,然后我在这个环境中使用compilInstruction:

def compilProgram(fichierSortie, nbrRegDispo, AST):
    DICOFUN={}
    for elt in AST.children:
        if elt.type=='fonctionDef':
            DICOFUN[elt.leaf]=elt.children
            continue
        else :
            pass
    env=environnement(nbrRegDispo)
    print(type(env))
    compteurLabel=0
    for elt in AST.children:
        if elt.type!='fonctionDef':
            (env, compteurLabel)=compilInstruction(env, fichierSortie, elt, compteurLabel)

compilProgram 上的打印是在我将其交给compilInstruction 之前检查env 是什么(因为我有问题)。

def compilInstruction(env, fichierSortie, instruction,compteurLabel):
    print(type(env))
    envInterne=environnement(env.taille, env.reg, env.raccess, env.faccess)
    ...

我尝试了许多其他方法来复制env,但问题似乎不是来自它。 这是我在属性参数上尝试 compilProgram 时得到的结果:

<class 'Environnement.environnement'> (this is the print from compilProgram)
<class 'Environnement.environnement'> (this is the print from compilInstruction)
<class 'NoneType'> (this again comes from the print in compilInstruction)
...
AttributeError: 'NoneType' object has no attribute 'taille'

为什么compilInstruction 中的打印会运行两次,为什么env 在两次运行之间消失了?

【问题讨论】:

标签: python class


【解决方案1】:

你有两个打印语句,它解释了两次打印。

您将使用第一次调用 compilInstruction 函数的返回值覆盖 env。因此,该函数返回一个 None 值作为它返回的元组的第一个元素。

【讨论】:

  • 好吧,我有 3 个打印来自代码中的 2 个打印(我已经编辑了我的问题以指出它)
  • @user1483213 顺便说一句,您为什么接受与此信息相同的更新答案?
【解决方案2】:

您不止一次拨打compilInstruction:

for elt in AST.children:
    if elt.type!='fonctionDef':
        (env, compteurLabel)=compilInstruction(env, fichierSortie, elt, compteurLabel)

您在 AST.children 中有多个 elt 不是“fonctionDef”(错字??),因此您不止一次调用 compilInstruction。这就是为什么您可以从中获得不止一张印刷品的原因。 compilInstruction 的返回值被分配给env 和compteurLabel,所以env 被None 覆盖。

【讨论】:

  • 好的,我现在知道了,我会检查我的 compilInstruction 函数。非常感谢!
  • 非常感谢,在代码中没有进一步发现错误。一定是太累了。还是谢谢你!!
猜你喜欢
  • 1970-01-01
  • 2012-06-19
  • 2016-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-14
  • 1970-01-01
相关资源
最近更新 更多