从python中的创建者访问add方法中的字典

时间:2018-03-24 17:57:13

标签: python python-3.x dictionary

我必须实现一个名为Marathon的类。在创作者中,必须声明一个带有键' runner'和价值的时间'我在创作者中声明了字典。然后当我尝试在寄存器方法中使用该字典时,出现错误NameError: name 'my_marathon' is not defined。有人能告诉我如何通过我的注册方法访问该字典吗?

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

1 个答案:

答案 0 :(得分: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)

使用self引用实例变量。