Home > Mobile >  Python - TypeError: __init__() takes 3 positional arguments but 4 were given
Python - TypeError: __init__() takes 3 positional arguments but 4 were given

Time:10-10

I've seen this question before, but I couldn't resolve the issue...

I've only started to learn to program for the past 4 days, so it's probably something very basic. Here is my code from two diff files:

from Children import children_eating

keely_kids = [
    "Ella",
    "Jonathan",
    "Nathanael",
    "Daniel"
]

what_kids_chewing = [
    children_eating(keely_kids, [0], True),
    children_eating(keely_kids, [1], True)
]

#print(what_kids_chewing)

class children_eating:
    def __init__(self, name, is_chewing):
    self.name = name
    self.is_chewing = is_chewing

CodePudding user response:

In __init__ you do not have to pass self. It is done automatically. The keely_kids, [0], is also not a correct way to use a table. You should use keely_kids[0]. In summary, use:

what_kids_chewing = [
    children_eating(keely_kids[0], True),
    children_eating(keely_kids[1], True)
]

CodePudding user response:

when passing a list using indexes it's like this children_eating(keely_kids[0], True),. Just overwrite the line and your code will work.

what_kids_chewing = [ children_eating(keely_kids[0], True), children_eating(keely_kids[1], True) ]

CodePudding user response:

def __init__(self, name, is_chewing) means , you can only pass 2 arguments(name and is_chewing) to the class's initializer. First parameter which is self is automatically filled by a reference to the newly created object by Python. So it is reserved.

But in children_eating(keely_kids, [0], True) you passed 3 three arguments, also Python itself filled the first one(passes one). This is why you get that error.

CodePudding user response:

The class children_eating has a constructor (the __init__ method) accepting only two elements, as explained below:

class children_eating:
    def __init__(self, name, is_chewing):  
        # the inputs to this method are: "name" and "is_chewing"
        self.name = name
        self.is_chewing = is_chewing

In fact, the self refers to the class internal state, and it is automatically passed to the method by python itself. When you call the method, you can simply ignore the self. Just pass values for name and is_chewing. On the contrary, when you write:

children_eating(keely_kids, [0], True)

in both cases, you are giving too many inputs, getting the error:

__ init __() takes 3 positional arguments but 4 were given

which tells you that you are actually giving the method 4 parameters instead of 3. In fact, the method receives keely_kids, [0], and True, plus the self (which is automatically given internally).

You can correctly call the class constructor as:

children_eating(keely_kids[0], True)
  • Related