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

38,958

Solution 1

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

Solution 2

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)
Share:
38,958

Related videos on Youtube

Bilal Haider
Author by

Bilal Haider

Updated on July 09, 2022

Comments

  • Bilal Haider
    Bilal Haider almost 2 years

    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
    
    • ThiefMaster
      ThiefMaster about 12 years
      Fyi, your classes should inherit from object (google for python new-style classes if you are curious why)