这是导致我出现问题的python代码:
# -*- coding: utf-8 -*-
class ObjectType2 (object):
def __init__ (self):
self.name = ""
self.value2 = 0
class ObjectType1 (object):
def __init (self):
self.value = 0
self.variables = []
class MainStruct (object):
def __init__ (self):
index1 = 0
index2 = 0
self.objects1 = []
for index1 in [0, 1, 2]:
self.objects1.append(ObjectType1())
self.objects1[index1].value = index1
self.objects1[index1].variables.append(ObjectType2())
if __name__ == '__main__':
foobar = MainStruct()
for x in foobar.objects1:
print(x.value)
当我执行它时,我收到了以下错误消息:
Traceback (most recent call last):
File "C:\Users\Franck\Documents\Developpement\python\dbc_file_reader \test1.py", line 31, in <module>
foobar = MainStruct()
File "C:\Users\Franck\Documents\Developpement\python\dbc_file_reader\test1.py", line 25, in __init__
self.objects1[index1].variables.append(ObjectType2())
AttributeError: 'ObjectType1' object has no attribute 'variables'
看起来它与ObjectType1中的空列表初始化有关,但我无法弄清问题是什么。有人能指出我的问题在哪里吗?
答案 0 :(得分:4)
在
def __init (self):
应该是
def __init__(self):
↑↑
如果没有两个尾随下划线,这只是一个与其他方法一样的方法,而不是构造函数。