Python 列表值的意外更改

Python 列表值的意外更改,python,Python,这是我的班级: class variable(object): def __init__(self, name, name_alias, parents,values,table): #name of the variable self.name = "" 这是有问题的函数: f是一个file.txt文件(在“main function”中打开) 我的.txt文件是: VAR name MaryCalls VAR name JohnCalls VAR name Burg

这是我的班级:

class variable(object):
    def __init__(self, name, name_alias, parents,values,table):
    #name of the variable
    self.name = ""
这是有问题的函数:

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

我的.txt文件是:

VAR
name MaryCalls
VAR
name JohnCalls
VAR
name Burglary
VAR
name Earthquake
VAR
name Alarm
我在那份印刷品(以及清单)中得到的是:

警报

警报

警报

警报

警报

但我想:

玛丽考尔斯

约翰卡尔

入室盗窃

地震

警报

怎么了?为什么列表中以前的所有条目都在更改


谢谢大家!

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

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

如果执行
打印(变量列表)
,您将看到这一点:

等等。

1)如果要初始化
变量的构造函数中的名称,必须进一步缩进赋值

def __init__(self, name, name_alias, parents,values,table):
    #name of the variable
    self.name = ""
2) 您的主要问题是,您想用此行创建
变量的新实例:

x=variable;
你必须写:

x = variable();

主要问题是,当代码检测到以“VAR”开头的行时,它将类变量分配给x,而不是类的实例。要做到这一点,您需要调用最终调用类'
\uuu init\uuu()
方法(如果它有一个)的类。您的需要,但它需要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()
x=variable;
x = variable();
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()