文件附加和使用数组发生错误

2024-09-28 20:17:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了这样的代码:

    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]?你知道吗

先谢谢你


Tags: nameselfnoneobjectdeflinewidthcomponent
3条回答

您的__init__中出现了问题:

  def __init__(self, *component, **kwargs):

    self.name = kwargs.get('name')
    self.component = component

    self.lines = kwargs.get('lines', [])

会有用的。您需要linesname位于收集组件的*项之后。你知道吗

在python2中,不能以*命名属性,因此需要改用**kwargsget('name')以及get('lines')中的kwargs。你知道吗

get如果不提供默认值,只返回None,因此在这里可以得到self.name = None。如果要指定默认名称,可以

    self.name = kwargs.get('name', 'defaultname')

就像我为lines所做的那样。你知道吗

问题是在定义system时,在构造函数中将Component1作为line参数传递。因为python做了他能做的所有操作,如果操作合法的话,就不检查参数类型,所以这就通过了。你知道吗

也许在系统构造函数中检查给定的参数lines是否真的是list类型是个好主意,也许可以编写如下内容:

    if lines is None or not isinstance(lines, list):
            self.lines = []
    else:
            self.lines = lines

这样,您就可以在尝试附加到非列表对象之前知道问题。你知道吗

至于你问题的第二部分,你可以完全按照你的建议去做:

system1 = system([Component1, Component2, MyComponent], [])

(例如,如果您想创建一个包含3个组件的系统,并将空列表作为行的“控制台”)

第32行使用self.lines.append(line)。你知道吗

但是lines是用Component2初始化的类system的成员,该类型是没有方法append的类component。你知道吗

相关问题 更多 >