列表值的意外更改

时间:2013-12-08 15:35:29

标签: python

这是我的班级:

class variable(object):
    def __init__(self, name, name_alias, parents,values,table):
    #name of the variable
    self.name = ""

这是有问题的功能:

f是文件.txt文件(在“main function”中打开)

def read_problem(f):
    list_of_variables=[]
    entry=0;

    for line in f:
        words = line.split()

        #enters only if it's not a comment
        if (words[0]!='#'):

            if (words[0]=="VAR"):
                x=variable;
            elif (words[0]=="name"):
                x.name=words[1]
                list_of_variables.append(x)

    for i in range(len(list_of_variables)):
        print(list_of_variables[i].name)
    return

我的.txt文件是:

VAR
name MaryCalls
VAR
name JohnCalls
VAR
name Burglary
VAR
name Earthquake
VAR
name Alarm

我在该印刷品中获得的内容(因此,列表)是:

报警

报警

报警

报警

报警

但我想要:

MaryCalls

JohnCalls

地震

报警

怎么了?为什么列表的所有先前条目都在变化?

谢谢!

3 个答案:

答案 0 :(得分:4)

x=variable行使x引用班级variable。您永远不会创建该类的任何实例,而是反复修改类级变量name

在程序结束时,当您打印时,variable.name当然会为其分配最后一个值,在本例中为'Alarm'

如果你print(list_of_variables)

,你会看到这个
[<class '__main__.variable'>, <class '__main__.variable'>, 

x = variable更改为x = variable(),您会看到(例如):

[<__main__.variable object at 0x6ffffee65d0>, <__main__.variable object at 0x6ffffee6610>

答案 1 :(得分:2)

1)如果要在variable的构造函数中初始化名称,则必须进一步缩进分配。

def __init__(self, name, name_alias, parents,values,table):
    #name of the variable
    self.name = ""

2)您的主要问题是,您希望使用以下行创建variable的新实例:

x=variable;

你必须写:

x = variable();

答案 2 :(得分:0)

主要问题是当代码检测到以“VAR”开头的行时,它将类变量分配给x,而不是类的实例。要做到这一点,你需要调用最终调用类__init__()方法的类(如果有的话)。你的确如此,但是它需要5个参数,其中没有一个在创建时就知道了。

在这种情况下最简单的方法是为每个参数分配一个默认值,表示“还没有值”,并将这些值分配给正在创建的实例(self)。

这就是我的意思:

class Variable(object):
    def __init__(self, name="", name_alias="", parents=None, values=None, 
                 table=None):
        self.name = name
        self.name_alias = name_alias
        self.parents = parents
        self.values = values
        self.table = table

def read_problem(f):
    list_of_Variables=[]

    for line in f:
        words = line.split()

        # if not a comment
        if words[0] != '#':
            if words[0] == "VAR":
                x = Variable()  # construct empty Variable
            elif words[0] == "name":
                x.name = words[1]
                list_of_Variables.append(x)

    for var in list_of_Variables:
        print(var.name)
    return

def main():
    filename = 'variables.txt'
    with open(filename) as f:
        read_problem(f)

main()