Reputation: 75
I am trying to make a class which allows for initalization with either default values for arguments, or with the values passed to it. Furthermore, I want to be able to pass those arguments either as positional or as keyworded ones. It works with keyworded arguments, however, when I try creating it like foo = Foo(3)
with any number of positional arguments provided I get a TypeError: __init__() takes 1 positional argument but 2 were given
class Foo:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
args_list = OrderedDict()
args_list.update(x=1,
y=2,
z=3)
args_list.update(kwargs)
iter_args_list = enumerate(args_list)
for positional_arg in args:
(_, key_value) = next(iter_args_list)
args_list[key_value] = positional_arg
for argument_key, argument_value in args_list.items():
setattr(self, argument_key, argument_value)
Upvotes: 2
Views: 201
Reputation: 476594
The problem is probably that you pass the args
and kwargs
to the super()
and object
does not like that since the object
does not take (named or unnamed) parameters. So you should rewrite:
class Foo:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# ...
to:
class Foo:
def __init__(self, *args, **kwargs):
super().__init__()
# ...
Upvotes: 2