【问题标题】:TypeError while using ast使用 ast 时出现类型错误
【发布时间】:2021-09-06 22:56:16
【问题描述】:

我正在尝试使用 ast 阅读我的字典(在我的文件中)

import ast
import os

class just_a_class():
    def __init__(self, file,):
        self.file = file()
        self.read_file = open(self.file,'r+')

    def read_file(self):
        dict = ast.literal_eval(self.read_file.read())
        return 'Input: \n\n {}'.format(dict)

the_class = just_a_class("dict.txt")
print(the_class.self.read_file())

错误:

Traceback (most recent call last):
File "c:/Users/Barış/Desktop/Onemli_Programlarim/Connection_PL/conn.py", line      13, in <module>
the_class = just_a_class("dict.txt")
File "c:/Users/Barış/Desktop/Onemli_Programlarim/Connection_PL/conn.py", line 6, in __init__
self.file = file()
TypeError: 'str' object is not callable

【问题讨论】:

  • self.file = file() 删除那里的括号,file 是 str,你不应该调用它
  • 而且最好在完成后关闭打开的文件,最好不要给与Python内置冲突的变量命名,即@987654327 @ 这里(语法高亮也有帮助...)
  • 我认为错误回溯本身的答案很清楚 - “TypeError: 'str' object is not callable”,第 6 行。您正在尝试将字符串(文件)作为函数调用(文件())。正如@Altareos 所述,您需要将其替换为 self.file = file
  • 次要旁注:您不希望在此处使用模式 "r+"。您从文件中读取,从不写入,因此打开文件进行读取和写入是一种浪费,并且存在行为不当的风险,因为以读取它为目的而打开的文件现在也可能被意外写入。

标签: python python-3.x dictionary typeerror abstract-syntax-tree


【解决方案1】:

下面的代码类似于问题中使用的代码。我试过了 通过使用常见的技术和约定来提高可读性, 例如使用fname 作为文件名,而不是file,使用 上下文管理器来打开(和自动关闭)文件,以及大小写 对于类名。还将标志更改为 open() 调用为“r” 而不是 ShadowRanger 建议的“r+”。

import ast

class Just_a_class():
    def __init__(self, fname):
        self.fname = fname
    def read_file(self):
        with open(self.fname, 'r') as f:
            dict = ast.literal_eval(f.read())
        return 'Input: \n\n {}'.format(dict)

the_class = Just_a_class("dict.txt")
print(the_class.read_file())
# {'a': 5, 'b': 'hello'}

【讨论】:

  • 虽然这在技术上修复了代码,但它有点跳过了为什么它首先被破坏,同时进行了其他更改,使其不清楚实际问题(而不是糟糕的样式/设计)是什么在原始代码中。
  • @ShadowRanger:是的,我同意你的结论,但我不清楚如何描述修复背后的所有原因。我想我会尝试对其进行总结,然后展示能够捕捉原始代码中主要主题的工作代码。感谢您提供有关“r+”的提示;我没发现那个。
猜你喜欢
  • 2011-10-17
  • 2017-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-15
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多