从__init__获取文件名

只是试图获取要从init传递的文件名,这样我就不必在插入函数的参数中放入例如“ file.txt”。

class Simpledb():
      def __init__(self, filename):
          self.filename = filename

      def insert(self, key, value): 
          f = open(self.filename, 'a+')
          f.write(key + '\t' + value + '\n')
          f.close()

When used from another module with code from database2 import * and then Simpledb.insert('database.txt', name, number)(name and number are input strings), returns "AttributeError: 'str' object has no attribute 'filename'". How can I insert successfully?

评论
  • 半神经
    半神经 回复

    您需要在其他代码中初始化您的类,例如:

    from database2 import *
    
    myDB = Simpledb("database.txt")
    myDB.insert(name,number)
    

    让我知道是否有帮助!