0
class Tasks(object):
    def __init__(self, container=None):
        if container is None:
            container = []
        self.container = container


    def add(self,name,date,priority):
        self.container.append([name,date,priority])

    def __str__(self):
        return str(self.container)

    def __repr__(self):
        return str(self.container)

    def __getitem__(self, key):
        return Tasks(self.container[key])

    def __len__(self):
        return len(self.container)


class management(Tasks):
    def save(self):
        outfile = open ("tasks.txt","w")
        outfile.write(("\n".join(map(lambda x: str(x), task))))

        print task
        outfile.close ()
    def load(self):
        load_file = open("tasks.txt","r")
        task = load_file.readlines()
        print task
        #this line is the attempt to convert back into the original format
        Tasks(add(task))




task = Tasks()        
if __name__== "__main__":

    p = management(Tasks)

    #task.add("birthday","27092012","high")
    #task.add("christmas","20062000","medium")
    #task.add("easter","26011992","low")
    print task

    #print len(task)
    #p.save()
    p.load()


    print "test",task
    print len(task)

我的代码的最终目的是生成一个任务管理器(待办事项列表)

上面的代码生成一个 [name,date,priority] 列表,然后将其保存在一个名为 tasks.txt 的文本文件中 - 据我所知,这可以完美运行(只要我注释掉 p.load)。

然而......加载函数加载文件,但我需要能够打印它作为打印任务加载的列表,就像我在注释掉 p.load() 时所做的那样。

这将使我能够最终,删除,排序等任务

提前致谢

我为我不知道如何在第一行表达的糟糕问题道歉

编辑: 我考虑过酸洗可以保留列表格式,但我认为它不能解决我能够将参数传递回 Tasks() 类以便能够将它们打印为打印任务的问题

编辑 2 加载函数现在读取

 def load(self):
     with open("tasks.txt", "r") as load_file:
         tasks = [ast.literal_eval(ln) for ln in load_file]
     print tasks
     for t in tasks:
         todo.add(t)

显然(或者至少我认为)我收到错误 NameError: global name 'todo' is not defined 我已经尝试使用 task.add(t) 并得到 TypeError: add() 需要 4 个参数(给定 2 个)

我也尝试使用 Tasks.add(t) 并得到错误 TypeError: unbound method add() must be called with Tasks instance as first argument (得到列表实例代替)

我显然不明白代码,你能解释一下吗,谢谢。

编辑 3 while True: menu_choice = int(input("Select a number from the menu"))

try:
    if menu_choice == 1:

        task = raw_input ("task")
        date = raw_input ("date")
        priority = raw_input ("priority")
        tasks = Tasks([(task,date,priority)])
        print tasks


    elif menu_choice == 2:
        print tasks
    elif menu_choice == 3:
        tasks.save()
    elif menu_choice == 4:
        tasks.load()
except:
    print sys.exc_info()

这每次都会重写任务而不是附加它,有什么想法吗?菜单选项 2,3,4 也不起作用,因为任务不是全局定义的,不知道如何解决这个问题?也许回来?

4

2 回答 2

2

假设您的名称、任务和优先级是简单的 Python 对象,您可以使用以下命令加载它们ast.literal_eval

with open("tasks.txt", "r") as load_file:
    # no need for readlines, just loop over the file!
    tasks = [ast.literal_eval(ln) for ln in load_file]

然后循环过来tasks把里面的对象放到一个Tasks对象里面。请注意,这是Tasks(add(task))行不通的。您需要有一个类型的对象Tasks,将其传递给load(我们称之为todo),然后执行

for t in tasks:
    todo.add(t)

顺便说一句,你不需要management上课。两个独立的功能就可以了。Python 不是 Java

于 2012-05-20T08:41:26.250 回答
0

尝试一种不同的、更 Pythonic 的方法。与其说是答案,不如说是另一种选择。编辑三次以考虑对新功能的许多请求。

import pickle

class TasksError(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

class Task(object):
    def __init__(self, task = () ):
        if task ==():
            raise TasksError('Empty task.')
        self.name = task[0]
        self.date = task[1]
        self.priority = task[2]

    def __str__(self):
        output = '''Name: %s
Date: %s
Priority: %s
''' % ( self.name,
        self.date,
        self.priority )
        return output

class Tasks(object):
    def __init__(self, container = []):
        self.container = [ Task(todo) for todo in container ]

    def find_by_priority(self, priority = 'high'):
        # example method to seek and print high priority tasks
        # using this example, you will be able to conduct many
        # types of searches
        results = [ task
                   for task in self.container
                   if task.priority == priority ]
        return results

    def sort_by_date(self):
        # example method of how to sort, again, many other
        # ways of sorting can be implemented, this is just
        # to demonstrate the principle
        # for more info on sorting,
        # visit:  http://wiki.python.org/moin/HowTo/Sorting
        self.container = sorted(self.container,
                                key=lambda task: task.date)

    def add(self, task):
        if task == '':
            raise TasksError('Empty task')
        self.container.append( Task(task) )

    def save(self):
        try:
            output = open('tasks.pkl', 'wb')
            pickle.dump(self.container, output)
            output.close()
        except:
            raise TasksError('Failed to save.')

    def load(self):
        try:
            pkl_file = open('tasks.pkl', 'rb')
            self.container = pickle.load(pkl_file)
            pkl_file.close()
        except:
            raise TasksError('Failed to load')

    def __str__(self):
        output = '\n'.join( [ str(todo) for todo in self.container ] )
        return output

if __name__== "__main__":
    divider = '-' * 30 + '\n'

    tasks = Tasks( [("birthday","20121111","high"),
                    ("christmas","20121225","medium"),
                    ("easter","20120405","low")] )
    print 'Three original tasks:\n'
    print tasks # prints out three tasks
    print divider

    tasks.add( ("new-task","20120320","high") )
    print 'Three original plus one new task:\n'
    print tasks # prints out four tasks
    print divider

    tasks.save() # pickles the task list and saves to disk

    tasks = Tasks( container = [] ) # creates a new, empty task list
    print 'Empty task list:\n'
    print tasks # prints out empty list
    print divider

    tasks.load() # loads the pickled list
    print 'The four pickled tasks, reloaded:\n'
    print tasks # prints out four tasks
    print divider

    while True:
        print divider, '''Make your selection:
1. Add new task
2. Print all tasks
3. Save tasks
4. Load tasks from disk
5. Find high priority tasks
6. Sort by date
<ENTER> to quit
'''
        try:
            menu_choice = int(input("Select a number from the menu: "))
        except:
            print 'Goodbye!'
            break

        if menu_choice == 1:
            # note: no error checking here
            # even an empty input is accepted
            task = raw_input (">>> Task: ")
            date = raw_input (">>> Date as string YYYYMMDD: ")
            priority = raw_input (">>> Priority: ")
            todo = (task, date, priority)
            # note that here you should add a task
            # your method created a NEW task list
            # and replaced the old one
            tasks.add( todo )
            print tasks
        elif menu_choice == 2:
            print divider, 'Printing all tasks'
            print tasks
        elif menu_choice == 3:
            print divider, 'Saving all tasks'
            tasks.save()
        elif menu_choice == 4:
            print divider, 'Loading tasks from disk'
            tasks.load()
        elif menu_choice == 5:
            print divider, 'Finding tasks by priority'
            results = tasks.find_by_priority(priority='high')
            for result in results: print result
        elif menu_choice == 6:
            print divider, 'Sorting by date'
            tasks.sort_by_date()
            print tasks

重要说明:这是作为练习生成的代码,用于演示您正在寻求实现的许多功能,并展示正确使用面向对象设计如何允许您封装每个任务和任务列表并轻松操作它们。它还演示了使用 pickle 作为您在原始问题中使用的文本文件实现的 Pythonic 替代方案。它还演示了按字段搜索和排序,实现了两个简单的方法。

如果你对这个项目很认真,你需要看看一个合适的数据库,比如SQLite,它允许人们搜索、排序、更新、添加和删除记录的功能比你手动可靠地实现的要多。

于 2012-05-20T09:34:51.963 回答