__init__() missing 1 required positional argument: 'quantity'

Question:

I am getting the error as shown in the question, and I can’t figure out why. Even when trying other Stack Overflow methods of fixing this it doesn’t work.

class Item(object):
    def __init__(self, name, style, quantity):
        self.name = name
        self.style = style
        self.quantity = quantity
    
class Weapon(Item):
    def __init__(self, name, style, quantity=1):
        Item.__init__(name, style, quantity,)

Bow = Weapon(name = "Bow", style = "WRanged", quantity = 1)

The lines affected with the error codes:

Traceback (most recent call last):
  File "C:StuffSGWorkInventory.py", line 33, in <module>
    Bow = Weapon(name = "Bow", style = "WRanged", quantity = 1)
  File "C:StuffSGWorkInventory.py", line 12, in __init__
    Item.__init__(name, style, quantity,)
TypeError: __init__() missing 1 required positional argument: 'quantity'
Asked By: aimcreeper

||

Answers:

Change

Item.__init__(name, style, quantity,)

for

super().__init__(name, style, quantity)
Answered By: rafaelc

Simply use super for inheritance in Python (read here for more details):

class Weapon(Item):
     def __init__(self, name, style, quantity = 1):
         super(Weapon, self).__init__(name, style, quantity)
Answered By: Matheus Portela

You’re missing self in the Item._init__(). You can either:

  1. Add self:

     class Weapon(Item):
         def __init__(self, name, style, quantity=1):
             Item.__init__(self, name, style, quantity)
    
  2. Use super:

     class Weapon(Item):
         def __init__(self, name, style, quantity=1):
             super(Weapon, self).__init__(name, style, quantity)
    
Answered By: Juan Sanchez

Calling Item.__init__ directly means you need to pass self as the first argument. Simply doing Item.__init__(name, style, quantity) means it thinks that name is the Item instance (self) and style is the name, quantity is the style and quantity is missing.

So you can just specify self as the first argument:

Item.__init__(self,name, style, quantity)

Or since the __init__ is in no way different you can just not override it at all:

class Weapon(Item):
     #default to using Item.__init__, no problem here
##    def __init__(self, name, style, quantity = 1):
##        Item.__init__(name, style, quantity)

Although this means that quantity is now a required argument but I don’t think that will be an issue.

Or as others have already said you can use super() to figure out what methods it should use.

Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.