Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: __init__() takes exactly 3 arguments (2 given)

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)

and this is the error I get

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
like image 557
Bilal Haider Avatar asked Feb 25 '12 14:02

Bilal Haider


2 Answers

The __init__() definition calls for 2 input values, startValue and firstValue. You have only supplied one value.

def __init__(self, startValue, firstValue):

# Need another param for firstValue
a = SimpleCounter(5)

# Something like
a = SimpleCounter(5, 5)

Now, whether you actually need 2 values is a different story. startValue is only used to set the value of firstValue, so you could redefine the __init__() to use only one:

# No need for startValue
def __init__(self, firstValue):
  self.count = firstValue


a = SimpleCounter(5)
like image 154
Michael Berkowski Avatar answered Nov 10 '22 21:11

Michael Berkowski


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

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
like image 38
senderle Avatar answered Nov 10 '22 22:11

senderle