其他分享
首页 > 其他分享> > TypeError: missing 1 required positional argument

TypeError: missing 1 required positional argument

作者:互联网

源代码:

class Caculate_Salary:
    def __call__(self,salary):
        monthySala=salary*1
        YearSala=salary*12
        print("算工资了")
        return dict(Monthy_Sala=monthySala,Year_Sala=YearSala)
a=Caculate_Salary()
a()
报错:
Traceback (most recent call last):
  File "D:/pycharm/pycharm_baishi/dui_xiang/cell__.py", line 8, in <module>
    a()
TypeError: __call__() missing 1 required positional argument: 'salary'

原因1:

由于__call__传入参数salary,导致实例化a后,调用该方法时,必须传入参数
所以可以将a()改为a(5000)

class Caculate_Salary:
    def __call__(self,salary):
        monthySala=salary*1
        YearSala=salary*12
        print("算工资了")
        return dict(Monthy_Sala=monthySala,Year_Sala=YearSala)
a=Caculate_Salary()
a(20000)
#执行结果
算工资了

原因2:

salary改为==*salary==(不定参数:可以不传参数,在实例调用该方法时)

class Caculate_Salary:
    def __call__(self,*salary):
        monthySala=salary*1
        YearSala=salary*12
        print("算工资了")
        return dict(Monthy_Sala=monthySala,Year_Sala=YearSala)
a=Caculate_Salary()
a()
####执行结果:
算工资了

Process finished with exit code 0

标签:salary,__,TypeError,required,positional,monthySala,Salary,call,YearSala
来源: https://blog.csdn.net/weixin_44719529/article/details/117382208