Search code examples
pythonclassmethodsconstructorinstance

Getting an error: object() takes no parameters in Python


I am getting TypeError says that objects takes no parameter.

I don't know what's wrong with my code. Can anyone help me to figure it out.

class Animal:

    def _init_(self, color):
        self.color = color
    
bingo = Animal("Brown")

print(bingo.color)

Solution

  • You are considering _init_ method as the constructor of your Animal class. But, you need to put double underscores before and after your constructor like this. The following code works fine:

    class Animal:
        def __init__(self, color):
            self.color = color
    
    bingo = Animal("Brown")
    print(bingo.color)
    

    If you do not want to change the name of your _init_ method, you need to call it differently like this:

    class Animal:
        def _init_(self, color):
            self.color = color
    
    bingo = Animal()
    bingo._init_("Brown");
    print(bingo.color)
    

    This should also work fine.