"Unexpected keyword argument" in super () .__ init __ ()

I am writing a small text game. I keep getting an error while trying to define a class variable.

Here's the class code:

class Scenery(): def __init__(self,name,description): self.name=name self.description=description class Door(Scenery): def __init__(self,openstatus,lockstatus): self.openstatus=openstatus self.lockstatus=lockstatus super().__init__(name,description,openstatus,lockstatus) class CageDoor(Door): def __init__(self): super().__init__(lockstatus=False, openstatus=False, name="Cage Door", description="It the door to the cage.") 

Code main.py:

 from tiles import CageDoor CageDoor = CageDoor() 

And the error:

  File "main.py", line 3, in <module> CageDoor = CageDoor() *File Location* name="Cage Door" TypeError: __init__() got an unexpected keyword argument 'name' 
+5
source share
2 answers

Door __init__ does not accept name or description , so a call to CageDoor.__init__ (which transfers control to Door.__init__ because super() determines that this is the next class in the inheritance hierarchy) will fail.

Change Door.__init__ to:

 class Door(Scenery): def __init__(self,openstatus,lockstatus, *args, **kwargs): self.openstatus=openstatus self.lockstatus=lockstatus super().__init__(*args, **kwargs) 

and then it will easily go through all the arguments except the two that it uses for the next __init__ in the chain. The advantage of receiving and sending *args and **kwargs is that even if the prototype of the Scenery constructor changes, Door not required; callers will need to pass the correct arguments if no default values ​​are given (so adding new arguments to the Scenery constructor without providing useful default values ​​is a bad form), but Door remains stable.

+6
source

When using super, it is important that all methods in the call chain use the same interface. Here you Door do not accept name or description . And Scenery does not accept openstatus or lockstatus . You must use each method in the *args and **kwargs call chain so that it can ignore parameters that it does not need. For more information see this post.

In this example, this means rewriting Door and Scenery as follows:

 class Scenery(): def __init__(self,name,description, *args, **kwargs): self.name=name self.description=description class Door(Scenery): def __init__(self openstatus,lockstatus, *args, **kwargs): self.openstatus=openstatus self.lockstatus=lockstatus super().__init__(*args, **kwargs) 
+1
source

Source: https://habr.com/ru/post/1238440/


All Articles