【问题标题】:how to create a dictionary/list/class created from raw_input如何创建从 raw_input 创建的字典/列表/类
【发布时间】:2014-05-02 19:31:27
【问题描述】:

我对 python 很陌生,我正在尝试制作一个非常基本的 VM,能够制作和读取“文本文件”(格式化字符串)。

现在,将有一个命令允许用户创建文件。该文件存储为一个类,但我不确定如何做这样的事情-

def filecreate(filename,contents):
    filename = contents
filecreate(str(raw_input("File Name: ")), insertcontenthere)

尝试在 idle/pycharm 中执行类似操作时,您不能这样做,因为它会因为文件名未定义而对您大喊大叫。

我已经研究了构造函数,但我不知所措。答案可能很明显,我没有看到,但我找不到。

(可能已经回答了,但由于措辞原因,我无法准确搜索。)

【问题讨论】:

  • 也许你应该用英语解释你希望代码实际做什么。
  • 用户通过 raw_input 输入命令创建文件,然后程序使用文件类创建一个新对象。
  • 他需要一个文件系统,仅此而已。他试图获取用户输入的文件名,然后将文件的内容作为变量分配给该文件名。他可以这样做,但需要一个文件系统作为字典来存储它。
  • 亚当·史密斯做对了。基本上就是这样。

标签: python list class dictionary vm-implementation


【解决方案1】:

您必须以某种方式创建文件系统。如果我可以提出一些建议:

class FileSystem(dict):
    # I'm not really sure what you need a file system
    # to do specifically. Probably things like
    # FileSystem.listdir but this is kind of beyond the
    # scope of this question

fs = FileSystem()

def filecreate(filename,contents):
    global fs
    fs[filename] = contents

filecreate(str(raw_input("File Name: ")), insertcontenthere)

FileSystem 中实现这一切可能不是一个坏主意,因此您将改为调用fs.filecreate(raw_input(), content)。此外,您永远不需要在raw_input 上调用str——它总是会返回一个字符串。

【讨论】:

  • 实际上,实际上,这比为每个文件创建一个新文件类更“省电”和更快,对吧?
  • 我会让 filecreate 成为 FileSystem 的一个实例方法。
  • @dano 我只是在编辑它!不先设计就编写文件系统并不是我的强项! :)
  • @user3348394 我绝对建议创建一个包含相关信息的class File。将 File 实例存储在您的 FileSystem 中的适当位置并称之为好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-01
  • 1970-01-01
  • 2022-11-18
  • 2018-12-17
  • 1970-01-01
  • 1970-01-01
  • 2018-03-21
相关资源
最近更新 更多