因为我是新来的stackoverflow社区,我不知道我是否应该将此作为一个新问题或延续问题,我在这里问error with appending to a file and using an array。关于编写一个类的属性的元组错误
它基本上是相同的代码从那里只有一个额外的行:
class component(object):
def __init__(self,
name = None,
height = None,
width = None):
self.name = name
self.height = height
self.width = width
class system(object):
def __init__(self,
name = None,
lines = None,
*component,
**kwargs):
self.name = kwargs.get('name')
self.component = component
self.lines = kwargs.get('lines') or []
def writeTOFile(self,*component):
self.component = component
line =" "
self.lines.append(line)
line= "#----------------------------------------- SYSTEM ---------------------------------------#"
self.lines.append(line)
line = "Width = %d" % component.width
self.lines.append(line)
def writeFile(self):
ef = open('file1.d', 'w')
ef.write('\n'.join(self.lines))
ef.close()
Component1 = component (name = 'C1',
height = 500,
width = 400)
Component2 = component (name = 'C2',
height = 600,
width = 700)
Component_list = [Component1, Component2]
system1 = system(Component_list)
system1.writeTOFile(Component_list)
system1.writeFile()
我添加的路线是这样的:
line = "Width = %d" % component.width
self.lines.append(line)
我得到的错误是这样的:
Traceback (most recent call last):
File "C:\Python27\Work\trial2.py", line 55, in <module>
system1.writeTOFile(Component_list)
File "C:\Python27\Work\trial2.py", line 37, in writeTOFile
line = "Width = %d" % component.width
AttributeError: 'tuple' object has no attribute 'width'
类组件显然有一个叫做width的属性,所以我不明白为什么会出现这个错误。 我明白,组件是一个组件数组,所以这可能是原因...但我试图在(组件)范围内使用for,但显然我缺乏使其工作的技能。 在此先感谢。
不完全。他的'__init__'严重受伤。如果他使用** kwargs,他不需要命名参数'name'和'lines' –
啊,我没有注意到他从我在最后一个答案中所做的更改中移除了他们。谢谢。 – agf
好男人!谢谢!我认为我对几件事情感到非常困惑。 – caran