我写了这样的代码:
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'
我真的不知道怎么修。你知道吗
还有一种方法可以将system1定义为system(Component),其中Component=[Component1,Component2,…Componentn]?你知道吗
先谢谢你
您的
__init__
中出现了问题:会有用的。您需要
lines
和name
位于收集组件的*
项之后。你知道吗在python2中,不能以
*
命名属性,因此需要改用**kwargs
和get('name')
以及get('lines')
中的kwargs
。你知道吗get
如果不提供默认值,只返回None
,因此在这里可以得到self.name = None
。如果要指定默认名称,可以就像我为
lines
所做的那样。你知道吗问题是在定义
system
时,在构造函数中将Component1
作为line
参数传递。因为python做了他能做的所有操作,如果操作合法的话,就不检查参数类型,所以这就通过了。你知道吗也许在系统构造函数中检查给定的参数
lines
是否真的是list类型是个好主意,也许可以编写如下内容:这样,您就可以在尝试附加到非列表对象之前知道问题。你知道吗
至于你问题的第二部分,你可以完全按照你的建议去做:
(例如,如果您想创建一个包含3个组件的系统,并将空列表作为行的“控制台”)
第32行使用
self.lines.append(line)
。你知道吗但是lines是用
Component2
初始化的类system
的成员,该类型是没有方法append
的类component
。你知道吗相关问题 更多 >
编程相关推荐