Python 3错误:RuntimeError: super():没有参数。

48

为什么会出现这个错误?有人能帮我解决这个问题吗?我试图在Progress.display()中调用类项目的显示函数,或者是否有其他方法来显示用户的输入?

还有,如何同时输入Stages类和Progress类?感谢帮助。

super().display()
RuntimeError: super(): 没有参数

以下是代码:

class Project:
    def __init__(self, name="", job="", **kwargs):
        super().__init__(**kwargs)
        self.name = name
        self.job = job

    def display():
        print("name: ", (self.name))
        print("job: ", (self.job))

    @staticmethod
    def prompt_init():
        return dict(name=input("name: "), job=input("job: "))


class Stages(Project):
    def __init__(self, stages="", **kwargs):
        super().__init__(**kwargs)
        self.stages = stages

    def display(self):
        super().display()
        print("stages: ", (self.stages))

    @staticmethod
    def prompt_init():
        parent_init = Project.prompt_init()

        choice = None
        while choice not in (1, 2, 3, 4, 5, 6):

            print("Insert your stage now: ")
            print("1. Planning")
            print("2. Analysis")
            print("3. Design")
            print("4. Implementation")
            print("5. Testing")
            print("6. Release")

            choice = input("enter your choice: ")
            choice = int(choice)

            if choice == 1:
                stages = "Planning"
            elif choice == 2:
                stages = "Analysis"
            elif choice == 3:
                stages = "Design"
            elif choice == 4:
                stages = "Implementation"
            elif choice == 5:
                stages = "Testing"
            elif choice == 6:
                stages = "Release"
            else:
                print("no such input, please try again")

            print(name)
            print(stages)


class Progress(Project):
    def __init__(self, progress="", **kwargs):
        super().__init__(**kwargs)
        self.progress = progress

    def display(self):
        super().display()
        print("progress: ", (self.progress))

    @staticmethod
    def prompt_init():
        parent_init = Project.prompt_init()

        choice = None
        while choice not in (1, 2, 3, 4):

            print("1. 25%")
            print("2. 50%")
            print("3. 75%")
            print("4. 100%")

            choice = input("enter your choice[1-4]: ")
            choice = int(choice)

            if choice == 1:
                progress = "25%"
            elif choice == 2:
                progress = "50%"
            elif choice == 3:
                progress = "75%"
            elif choice == 4:
                progress = "100%"
            else:
                print("no such input, please try again")

            print(progress)
        parent_init.update({"progress": progress})
        return parent_init


class A(Stages, Progress):
    def prompt_init():
        init = Stages.prompt_init()
        init.update(Progress.prompt_init())
        return init

    prompt_init = staticmethod(prompt_init)


class New:
    type_map = {("stages", "progress"): A}

    def add_project_test(self, name, job, stages):
        init_args = Project.prompt_init()
        self.project_list.append(Project(**init_args))

    def __init__(self):
        self.project_list = []

    def display_project():
        for project in self.project_list:
            project.display()
            print()

    def add_progress(self):
        init_args = Progress.prompt_init()
        self.project_list.append(Progress(**init_args))

    def add_project(self):
        ProjectClass = self.type_map[A]
        init_args = ProjectClass.prompt_init()
        self.property_list.append(ProjectClass(**init_args))


my_list = New()
my_list.add_progress()
my_list.display_project()

1
可能是[super()和@staticmethod交互]的重复问题(https://dev59.com/DV8d5IYBdhLWcg3weiF-)。 - Green Cloak Guy
4
如果有其他人发现这个问题和标题相似,但是并非同一个问题:您是否尝试在类本身而不是在 def __init__(self): 方法中调用 super().__init__()?将会引发相同的错误。 - Michael Scott Asato Cuthbert
4个回答

44
不是百分之百解决问题的方法,但是同样的错误。发给那些和我有相同问题的谷歌用户们,带着爱意。
在使用Python 3时,我因为忘记在方法中包含self而出现了这个错误。虽然是一件简单的事情,但有时候当你疲倦时最简单的事情会让你失误。
class foo(object):
    def bar(*args):
        super().bar(*args)

=> 运行时错误:super():缺少参数

记得包含你的self

class foo(object):
    def bar(self, *args):
        super().bar(*args)

41

这不是针对此问题的答案,但我在尝试在pdb shell中调用super时遇到了同样的错误,并最终陷入了解决它的兔子洞。为了使它正常运行,您需要在调用中添加要调用super的父类和self - super(<ParentClass>, self) - 在pdb中。至少要知道,在pdb中super不能按预期工作。我在那里并不是真正需要调用它,但它阻止了我找出其他东西为什么不起作用。


5
对于使用 PyCharm(在后台运行pdb)的用户也是一样。 - DankMasterDan
4
VS Code的用户也面临着同样的情况。 - Gary Wang
+1 Pycharm。但是为什么你要写成 ParentClass?它可以是您希望开始方法查找的任何类。对于遇到此问题的人,他们正在调用 super(the_Lowest_SubClass,self),而不是父类。 - Rick
有人告诉我,super()没有参数只能在类定义中使用。源代码在这里 https://github.com/python/cpython/blob/cd1fbbc81761dc26ce6daf724d57d48e965e5817/Objects/typeobject.c#L9060-L9061 。虽然我对源代码不太了解。 - Rick
这个回答值得更多的关注。 - user1315621

30

每次在方法中使用 super() 时,您需要处于实例方法或类方法中。您的 staticmethod 不知道其超类是什么。请注意:

class Funky:
    def groove(self):
        print("Smooth")

    @staticmethod
    def fail():
        print("Ouch!")

    @classmethod
    def wail(cls):
        print("Whee!")


class Donkey(Funky):
    def groove(self):
        print(super())

    @staticmethod
    def fail():
        try:
            print(super())
        except RuntimeError as e:
            print("Oh no! There was a problem with super!")
            print(e)

    @classmethod
    def wail(cls):
        print(super())


a_donkey = Donkey()
a_donkey.groove()
a_donkey.fail()
a_donkey.wail()

输出:

<super: <class 'Donkey'>, <Donkey object>>
Oh no! There was a problem with super!
super(): no arguments
<super: <class 'Donkey'>, <Donkey object>>

这是您的代码,已经进行了调试并增加了一些额外的功能和测试:

class Project:
    def __init__(self, name="", job="", **kwargs):
        super().__init__(**kwargs)
        self.name = name
        self.job = job

    def display(self):
        print("name: ", self.name)
        print("job: ", self.job)

    @staticmethod
    def prompt_init():
        return dict(name=input("name: "), job=input("job: "))


class Progress(Project):
    def __init__(self, progress="", **kwargs):
        super().__init__(**kwargs)
        self.progress = progress

    def display(self):
        super().display()
        print("progress: ", self.progress)

    @staticmethod
    def prompt_init():
        parent_init = Project.prompt_init()
        progress = input("your progress: ")
        parent_init.update({
            "progress": progress
        })
        return parent_init


class New:
    def __init__(self):
        self.project_list = []

    def display_project(self):
        for project in self.project_list:
            project.display()
            print()

    def add_project(self):
        init_args = Project.prompt_init()
        self.project_list.append(Project(**init_args))

    def add_progress(self):
        init_args = Progress.prompt_init()
        self.project_list.append(Progress(**init_args))


my_list = New()
my_list.add_project()
my_list.add_progress()
my_list.display_project()

谢谢你的帮助朋友!非常感激,我可以再问你一件事吗?现在我的代码中除了Progress类之外还有Stages类。我该如何同时输入它们?有什么想法吗? - Justin Junias
@JustinJunias 你确定Stages是一个类吗?还是它可能是Progress类的属性?比如,也许Progress可以有一个像现有的self.progress这样的变量,然后你可以创建一个名为set_stage(a_stage)(或advance_stage())的新方法来更新self.progress?你可能还需要更改progressprompt_init,不再为progress变量接受用户输入,而是始终将起始progress设置为“已添加到系统”或其他内容。只是一个想法 :-) - Rob Bricheno
作为参数传递的 cls 是什么意思? - Golden Lion
1
@GoldenLion 因为我们使用了 @classmethod 装饰器,所以这里的 cls 将包含实际的类对象。这很像在普通(实例)方法中第一个参数“self”被填充为类的实例一样,但在类方法中(按照惯例,在这种情况下是 PEP8),我们使用“cls”,并且被填充为类本身。 - Rob Bricheno

2
你可能不需要使用super(),只需直接引用超类。例如,我正在编写一个像this one这样的Django测试,但在我的情况下,AnimalTestCase继承了ParentTestCase。我希望AnimalTestCase中的fixture属性使用ParentTestCase中的所有相同的fixtures,并添加几个更多。但是调用super()从来没有起作用。最后,我意识到我可以直接引用ParentTestCase

fixtures = ParentTestCase.fixtures + ['more']

class ParentTestCase(TestCase):
    fixtures = ['bacteria', 'fungus', 'stalagtites', 'stalagmites']

    def setUp(self):
        # Test definitions as before.
        call_setup_methods()


class AnimalTestCase(ParentTestCase):
    fixtures = ParentTestCase.fixtures + ['vertebrata', 'invertebrate']

    def test_fluffy_animals(self):
        # A test that uses the fixtures.
        call_some_test_code()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接