误差追加到一个文件,并使用数组 [英] error with appending to a file and using an array
问题描述
我写了这个code:
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):
self.name = name
self.component = component
if lines is None:
self.lines = []
else:
self.lines = lines
def writeTOFile(self,
*component):
self.component = component
line =" "
self.lines.append(line)
line= "#----------------------------------------- SYSTEM ---------------------------------------#"
self.lines.append(line)
Component1 = component ( name = 'C1',
height = 500,
width = 400)
Component2 = component ( name = 'C2',
height = 600,
width = 700)
system1 = system(Component1, Component2)
system1.writeTOFile(Component1, Component2)
和我得到的错误:
Traceback (most recent call last):
File "C:\Python27\Work\trial2.py", line 46, in <module>
system1.writeTOFile(Component1, Component2)
File "C:\Python27\Work\trial2.py", line 32, in writeTOFile
self.lines.append(line)
AttributeError: 'component' object has no attribute 'append'
和我真的不知道如何解决它。
And I don't really know how to fix it.
也有定义我的系统1的系统(组件)的方式,其中组件= [的Component1,COMPONENT2,... Componentn]
Also is there a way for defining my system1 as system(Component) where component = [Component1, Component2, ...Componentn] ?
谢谢adavance
Thanks in adavance
推荐答案
您已经在得到的东西乱序__ __初始化
:
def __init__(self, *component, **kwargs):
self.name = kwargs.get('name')
self.component = component
self.lines = kwargs.get('lines', [])
将工作。您需要行
和名称
是 *
项目之后收集的组件。
Will work. You need lines
and name
to be after the *
item that collects the component.
在Python 2里,你不能再命名属性的后 *
,所以你需要改用 ** kwargs
和获取('名')
和的get('行')
从 kwargs
。
In Python 2, you can't then have named attributes after a *
, so you need to instead use **kwargs
and get('name')
and get('lines')
from the kwargs
.
GET
只返回无
,如果你不提供一个默认的,所以您将获得 self.name =无
在这里。如果要指定一个默认名称,你可以做
get
just returns None
if you don't supply a default, so you'll get self.name = None
here. If you want to specify a default name, you can do
self.name = kwargs.get('name', 'defaultname')
像我一样为行
。
这篇关于误差追加到一个文件,并使用数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!