Utoljára aktív 1731350954

TastyHint2.md Eredeti

If we have thought about this:


tasks = {}   # creates an empty dictionary

tasks['Buy Milk'] = 'not yet'
tasks['Start Lab'] = 'completed'

tasks['Finish Lab'] = 'not yet'

# to test if something is done?

task_name = 'Buy Milk'

if tasks[task_name] == 'not yet':
  # task is unfinished
  pass
else:
  # task is 'complete'
  pass


# to list all the tasks

for task_name, status in tasks.items():
  print("- ", task_name, status) 

We need to think about how to put thse ideas into the class. We might...

class Tasty:
  
  def __init__(self):
    self.tasks = {}

  def add_task(self, task_name):
    """
    Add a new task to the user tasks.
    """
    if task_name not in self.tasks:
        self.tasks[task_name] = "not yet"
    else:
        print("Task already added.")


  def display_tasks(self):
    for task_name, status in self.tasks.items():
      print("- ", task_name, status)

See how those things went from just trial code to methods in the class?

Yes, and... the self variable is how you know that thing is a method and not just a function.

If I paste the second code block into a Python interpreter...

>>> class Tasty:
...   
...   def __init__(self):
...     self.tasks = {}
... 
...   def add_task(self, task_name):
...     """
...     Add a new task to the user tasks.
...     """
...     if task_name not in self.tasks:
...         self.tasks[task_name] = "not yet"
...     else:
...         print("Task already added.")
... 
... 
...   def display_tasks(self):
...     for task_name, status in enumerate(self.tasks.items()):
...       print("- ", task_name, status)
... 
... 
>>> t = Tasty()
>>> t.add_task("Foo")
>>> t.add_task("Bar")
>>> 
>>> t.display_tasks()
-  0 ('Foo', 'not yet')
-  1 ('Bar', 'not yet')
>>> 

That's an example of how I might use the rough class here.

And if you're puzzled about my use of enumerate - I think now that it is wrong. It should probably be...

  def display_tasks(self):
    for task_name, status in self.tasks.items():
      print("- ", task_name, status)