类型错误:__init__() 正好有 3 个参数(给定 2 个) [英] TypeError: __init__() takes exactly 3 arguments (2 given)

查看:26
本文介绍了类型错误:__init__() 正好有 3 个参数(给定 2 个)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里看到了一些关于我的错误的答案,但对我没有帮助.我是 Python 课程的绝对菜鸟,9 月份才开始编写此代码.无论如何看看我的代码

I've seen a few of the answers on here regarding my error but its not helped me. I am an absolute noob at classes on python and just started doing this code back in September. Anyway have a look at my code

class SimpleCounter():

    def __init__(self, startValue, firstValue):
        firstValue = startValue
        self.count = startValue

    def click(self):
        self.count += 1

    def getCount(self):
        return self.count

    def __str__(self):
        return 'The count is %d ' % (self.count)

    def reset(self):
        self.count += firstValue

a = SimpleCounter(5)

这是我得到的错误

Traceback (most recent call last):
File "C:\Users\Bilal\Downloads\simplecounter.py", line 26, in <module>
a = SimpleCounter(5)
TypeError: __init__() takes exactly 3 arguments (2 given

推荐答案

你的 __init__() 定义需要 both 一个 startValue 一个firstValue.因此,您必须同时传递两者(即 a = SimpleCounter(5, 5))才能使此代码工作.

Your __init__() definition requires both a startValue and a firstValue. So you'd have to pass both (i.e. a = SimpleCounter(5, 5)) to make this code work.

然而,我觉得这里的工作存在一些更深层次的混乱:

However, I get the impression that there's some deeper confusion at work here:

class SimpleCounter():

    def __init__(self, startValue, firstValue):
        firstValue = startValue
        self.count = startValue

为什么要将startValue 存储到firstValue 中然后扔掉?在我看来,您错误地认为 __init__ 的参数会自动成为类的属性.事实并非如此.您必须明确分配它们.并且由于两个值都等于 startValue,因此您无需将其传递给构造函数.你可以像这样将它分配给 self.firstValue :

Why do you store startValue to firstValue and then throw it away? It seems to me that you mistakenly think that the parameters to __init__ automatically become attributes of the class. That's not so. You have to assign them explicitly. And since both values are equal to startValue, you don't need to pass it to the constructor. You can just assign it to self.firstValue like so:

class SimpleCounter():

    def __init__(self, startValue):
        self.firstValue = startValue
        self.count = startValue

这篇关于类型错误:__init__() 正好有 3 个参数(给定 2 个)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆