I am wondering how to initialize an object in python with only named args, and nothing else, if this is possible.
If the order of self.name = name and self.age = age are swapped, the error is with initializing age. I have these given as keyword args to the object, so why is that not enough? I saw a class in dive into python instantiated with explicitly named keyword arguments and their default (filename=None), so I assumed **kwargs would work too. Thank you
Best How To :
What you're missing is that kwargs need to be explicitly retrieved by name. Here's a modified version of your code, to illustrate. Note the initialization of
def __init__(self, **kwargs):
self.name = kwargs.get('name')
self.age = kwargs.get('age')
# you'll probably want to check that all required
# members were initialized.
bob = Person(name='bob', age=45)
<__main__.Person object at 0x1074e0bd0>