传递参数时如何正确使用super().__ init__? 程序:错误:

我对使用python进行OOP相对较新,并且正在编写一些程序来入门。问题在于,当我创建一个对象时,无论我使用多少个位置参数,参数数量似乎都会出错。

由于我是编程领域的新手,所以我不确定要尝试什么,但是我尝试尝试进行属性初始化阶段,但这完全禁用了该程序。

程序:

import random


class character:
    def __init__(self,name,skill,brains,home,strength,force):
        self.name = name
        self.skill = skill
        self.brains = brains
        self.home = home
        self.strength = strength
        self.force = force


class force_user(character):
    def __init__(self,force,dark_force,light_force):
        super().__init__(self,force)
        self.dark_force = dark_force
        self.light_force = light_force


class jedi(force_user):
    def __init__(self,light_force,master,rank):
        super().__init__(self,light_force)
        self.master = master
        self.rank = rank


a = jedi('Yoda',46,17,'Dagobah',34,97,2,10,"N'Kata Del Gormo",'Grand Master')

错误:

当对象'a'中具有'Grand Master''rank'参数时,我会收到以下消息:

Traceback (most recent call last):
  File [file directory],line 37,in <module>
    a = jedi('Yoda','Grand Master')
  File [file directory],line 32,in __init__
    super().__init__(self,light_force)
TypeError: __init__() takes 9 positional arguments but 10 were given

当我删除'Grand Master'参数时,我收到此错误:

Traceback (most recent call last):
  File [File Directory,"N'Kata Del Gormo")
TypeError: __init__() missing 1 required positional argument: 'rank'

我本人不太了解这个问题,但是任何帮助或建议都很好!

dukx95 回答:传递参数时如何正确使用super().__ init__? 程序:错误:

您应该更改

super().__init__(self,name,skill,brains,home,strength,force,dark_force,light_force)

super().__init__(name,light_force)

使用非静态实例方法时,您无需传递self(第一个参数)。

要特别清楚:如果您在jedi中有此方法

def printName(self):
    print(self.name)

您只需使用a.printName()而不是a.printName(a)来调用它。

本文链接:https://www.f2er.com/3152717.html

大家都在问