English 中文(简体)
如何从对象中删除
原标题:How to delete from an object
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]
        self.time = task[3]
        self.type = task[4]
        self.comment = task[5]

    def __str__(self):
        output =    Name: %s
Date: %s
Priority: %s
Time: %s
Type: %s
Comment: %s
    % ( self.name,
        self.date,
        self.priority,
        self.time,
        self.type,
        self.comment)
        return output

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




    def delete(self):

        x = 0
        for todo in self.container:

             x = x + 1
             print "Task Number",x,"
", todo
             delete = raw_input("what number task would you like to delete")
             if delete == "y":
                 del todo


        ############
        #x = 0
       # for task in self.container:
           # x = x+1
           #print "Task Number",x,"
", task
            #delete = raw_input("what number task would you like to delete")
            #if delete == "y":
                #del(task)







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






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

if __name__== "__main__":
    divider =  -  * 30 +  
 



    tasks = Tasks( container = [] ) # creates a new, empty task list

    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
7. Delete task

<ENTER> to quit
   
        try:
            menu_choice = int(input("Select a number from the menu: "))
        except:
            print  Goodbye! 
            break

        if menu_choice == 1:

            task = raw_input (">>> Task: ")
            date = raw_input (">>> Date as string YYYYMMDD: ")
            priority = raw_input (">>> Priority: ")
            time = raw_input (">>> Time: ")
            Type = raw_input (">>> Type Of Task: ")
            comment = raw_input (">>> Any Comments? ")
            todo = (task, date, priority, time, Type, comment)

            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
        elif menu_choice == 7:

            tasks.delete()

I have deleted parts of my code (hopefully nothing important). Im having trouble getting python to delete my tasks once added. Both methods defined as "def delete" give the error message type error: task/todo object does not support deletion. Does anyone know a way around this?

最佳回答

您不能从列表中删除这样的内容。 您的代码有两个问题 :

  • if you use for to loop through a iterable, you should not change it inside the loop.
  • to del from list you should use index.

尝试此 :

index = 0
while index < len(self.container):
    delete = raw_input("what number task would you like to delete")
    if delete == "y":
        del self.container[index]
    else:
        index += 1
问题回答

暂无回答




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签