【发布时间】: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 在两次运行之间消失了?
【问题讨论】:
-
与你的问题无关,但你一定会遇到这个问题:“Least Astonishment” in Python: The Mutable Default Argument