【问题标题】:Why doesn't the class take the info from list? Python为什么班级不从列表中获取信息? Python
【发布时间】:2021-08-25 03:17:56
【问题描述】:

所以我试图在使用类时从 txt 文件中获取信息到列表中。问题是,当我尝试告诉类获取属性时,它不会从列表中的元组中获取信息,而是告诉我分配给给定数字的信息。

下面是代码的主要部分。因此,当我调用 Portray 时,它应该将一个元组附加到 slst 作为 Notas 对象。问题是,它没有将整个 Notas(ranlst[1],ranlst[2],tranlst[3]) 视为一个对象,而是将每个输入都视为一个对象。因此,在下面的示例中,它应该打印: 查尔斯 70 4 小时

但是,它会打印: 查尔斯查尔斯查尔斯。

文件中的信息存储如下:

查尔斯

70

4 小时

知道为什么会这样吗?

class Notas:
    def __init__(self,nom,temp,nota):
        self.nom=nom
        self.temp=temp
        self.nota=nota

def Portray(): 
        file=open(path,'r',encoding='UTF8').readlines()
        lines=[line.strip()for line in file]
        ranlst=[]
        for part in lines:
          for leni in range(3):
            ranlst.append(str(part))
            slst.append(Notas(ranlst[0],ranlst[1],ranlst[2]))
          ranlst=[]
        print(slst[0].nom,slst[0].nota,slst[0].temp)

【问题讨论】:

  • 试试How to debug small programs文章或类似文章中的一些技巧?
  • slst 没有定义?此外,ranlst 将如何在初始运行中填充所有 3 个元素?提供的代码不会产生Charles Charles Charles 作为输出。请提供minimal, reproducible example
  • 顺便说一句,我认为您发布的程序与您运行的程序有些不同,因此请务必调试您实际测试的版本。

标签: python list class methods


【解决方案1】:
class Notas:
    def __init__(self,nom,temp,nota):
        self.nom=nom
        self.temp=temp
        self.nota=nota

def Portray(): 
        file=open(path,'r',encoding='UTF8').readlines()
        lines=[line.strip()for line in file]
        ranlst=[]
        for part in lines:
          for leni in range(3):
            ranlst.append(str(part)) ## HERE
            slst.append(Notas(ranlst[0],ranlst[1],ranlst[2]))
          ranlst=[]
        print(slst[0].nom,slst[0].nota,slst[0].temp)

HERE 语句运行 3 次。但是 str(part) 没有改变,因为它是外部 for 循环。所以,ranlst[0] [1] [2] 是一样的。这就是为什么你得到 3 Charles'。你可以像这样切换这两个 fors。

for leni in range(3):
    for part in lines:
              

【讨论】:

    猜你喜欢
    • 2011-02-26
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 2015-02-18
    相关资源
    最近更新 更多