python 对象从错误的文本文件中获取先前的对象属性,并从正确的文本文件中获取它们自己的属性

标签 python algorithm class object text-files

我正在尝试将文本文件中的数据加载到我的类的 python 对象中。然而,当我运行代码时,每个对象都将从以前的文本文件中加载的所有数据加载到它的属性中,我不知道这是怎么发生的。如果能提供一些帮助,我将不胜感激。

class Cocktail:

    recipe = []
    categories = []
    line = ''
    line2 = ''
    character = []
    name = ''
    path = ''

    def __init__(self):
        cocktails.append(self)
        #self.name = name

    def define(self, name):
        #print(self.name)
        self.name = name #the name of the cocktail is taken from a master text file
        self.path = self.name + '.txt' #each object will be linked to an individual text file containing its data
        with open(self.path, 'r') as cocktail_data: #opening the specific text file
            for line in cocktail_data:
                self.character = line.split(' ', 1)
                if self.character[0] == '#': #if the line starts with a # 
                    self.line = line.strip('#')
                    self.line2 = self.line.strip('/n')
                    self.categories.append(self.line2) #loads that lines data into the objects 'categories list'

                elif line.strip() == 'recipe': #when the recipe part of the text file is reached
                    break
            for line in cocktail_data: #continuing through the document 
                self.recipe.append(line.strip()) #adds each line of the rest of the document to the object's 'recipe' attribute

    def print(self): #for testing
        print(self.name) #prints the name of that cocktail that the object represents
        print(self.categories) #prints all the categories for that object
        print(self.recipe) #prints the recipe list for that object
        print('end') 
        #each new object seems to have the values (for its categories and recipe attributes) for all previous objects as well as its own
cocktails = []

with open('master.txt') as input_data:
    for line in input_data:
        name = line.strip() #the string that is the current line on the master text file
        cocktail = Cocktail() #creates object of Cocktail for each name in master document
        cocktail.define(name)
        cocktail.print()

这是我的 python shell 显示的内容:

cocktail1

[' a\n', ' b\n', ' c\n', ' d\n']

['one', 'two', 'three', 'end']

end

cocktail2

[' a\n', ' b\n', ' c\n', ' d\n', ' aq\n', ' bq\n', ' cq\n', ' dq\n']

['one', 'two', 'three', 'end', 'one q', 'two q', 'threeq', 'endq']

end

cocktail3

[' a\n', ' b\n', ' c\n', ' d\n', ' aq\n', ' bq\n', ' cq\n', ' dq\n', ' aw\n', ' bw\n', ' cw\n', ' dw\n']

['one', 'two', 'three', 'end', 'one q', 'two q', 'threeq', 'endq', 'onew', 'two w', 'threew', 'endw']

end

cocktail1 不应该有任何结尾有 'q' 或 'w' 的,cocktail 2 应该只有结尾有 'q' 的,cocktail 3 应该只有结尾有 'w' 的结束

最佳答案

您可能习惯于在类主体中声明实例属性的 Java 或其他 OO 语言 - 并且您正在尝试使用以下方法执行相同的操作:

class Cocktail:

    recipe = []
    categories = []
    line = ''
    line2 = ''
    character = []
    name = ''
    path = ''

    def __init__(self):
        cocktails.append(self)
        #self.name = name

但是在 Python 中,类主体中的任何声明都是针对 class 属性的。实例属性直接在实例上设置(使用 self.attrname = value 语句类型的内部方法)

对于上面的一些属性你不会看到问题,因为你使用不可变对象(immutable对象),并且当你在实例中设置它们时只是隐藏类属性 - 就像你做 self.name = name - 您单独在该实例上创建一个新的 name 属性。

但是,当您执行 self.categories.append(...) 时,您正在修改 cocktail 类中定义的单个 categories 对象(列表) , 并被所有鸡尾酒对象访问。

要修复您的行为,只需声明您的实例属性 - 这样做,例如:

class Cocktail:
    def __init__(self):
        self.recipe = []
        self.categories = []
        self.line = ''
        self.line2 = ''
        self.character = []
        self.name = ''
        self.path = ''

(但请记住,在需要在运行时设置变量或属性之前,您不必在 Python 中声明变量或属性 - 您只需在需要的方法中设置它们 - 这是您实际需要的唯一方法create 是包含列表的那些,因为你想将值附加到那些)。

关于python 对象从错误的文本文件中获取先前的对象属性,并从正确的文本文件中获取它们自己的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31194727/

相关文章:

algorithm - 寻找有关理解特定组合优化问题的建议

ruby - 为什么 Ruby 中的 MyClass.class.superclass 是 Module

python - 转换从 fetchall() 返回的类型

python - 带有 bool 语句的 Numpy 向量化函数赋值

python - 安装 gruobipy 包 - 错误

algorithm - dijkstra/prim 的算法...有点帮助?

algorithm - 最优选择算法

ios - 使用 Codable 使用相同的 key 解码不同的类

php - 我应该从我的代码中删除静态函数吗?

python - Django 表单