-2

I have to implement a class called Marathon. In the creator a have to declare a dictionary with key 'runner' and value 'time'. I declare the dictionary in the creator. Then when I try to use that dictionary in the register method an error appear NameError: name 'my_marathon' is not defined. Can someone tell me how I access to that dictionary from my register method?

class Marathon:

    def __init__(self):
        """Set up this marathon without any runners."""
        my_marathon = {'runner', 'time'}


    def register(self, runner):
        """Register the runner. Return nothing."""

        my_marathon['runner'] = runner
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
miCruQue
  • 23
  • 3
  • 1
    As written, you can't - it's a local in `__init__`, it gets dereferenced as soon as the method ends. You should read up on basic Python OOP - what you want is an *attribute*. See e.g. https://docs.python.org/3/tutorial/classes.html#a-first-look-at-classes – jonrsharpe Mar 24 '18 at 17:59

1 Answers1

0
class Runner:
    def __init__(self):
        self.time = -1

    def set_time(self, time):
        self.time = time


class Marathon:

    def __init__(self):
        """Set up this marathon without any runners."""
        self.runners = []


    def register(self, runner):
        """Register the runner. Return nothing."""

        self.runners.append(runner)

Use self to reference instance variables.

M. Shaw
  • 1,742
  • 11
  • 15