Python3类语法错误:非默认参数遵循默认参数

时间:2018-05-22 09:28:42

标签: python-3.x

我搞乱了Class'我有一个python3文件,代码如下:

class playerstats(object):
def __init__(self, name, baselevel=1, hp, mana, basedmg=0, atkdmg, basedef=0, chardef):
    self.name = name
    self.baselevel = baselevel
    self.hp = hp
    self.mana = mana
    self.basedmg = basedmg
    self.atkdmg = atkdmg
    self.basedef = basedef
    self.chardef = chardef
    return self.name, self.baselevel, self.basedmg, self.basedef
def selectedclass(self, chosenclass):
    if chosenclass == 'W' or chosenclass == 'w':
        self.hp = 100
        self.mana = 50
    elif chosenclass == 'M' or chosenclass == 'm':
        self.hp = 75
        self.mana = 100
    else:
        print('Error')
    return self.hp, self.mana

charcreation = playerstats('Tom', baselevel, self.chosenclass, self.chosenclass, basedmg, 0, basedef, 0)

self.chosenclass = 'w'

print(playerstats.hp)

当我运行它时,我收到此错误: 文件" .. \ Playground \",第2行     def init (self,name,baselevel = 1,hp,mana,basedmg = 0,atkdmg,basedef = 0,chardef):                  ^ SyntaxError:非默认参数遵循默认参数

有人可以帮助我理解为什么吗?

1 个答案:

答案 0 :(得分:2)

您需要更改__init__函数中的参数顺序。

通常,非默认参数不应该遵循默认参数,这意味着您无法在函数中定义(a="b",c)

函数中定义参数的顺序是:

  • 位置参数或非默认参数,即(a,b,c)
  • 关键字参数或默认参数,即(a =" bcd",r =" jef")
  • 仅限关键字参数,即(* args)
  • var-keyword参数即(** kwargs)