initializing python object with nothing but keyword args

4.5k views Asked by At

I am wondering how to initialize an object in python with only named args, and nothing else, if this is possible.

enter image description here

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

2

There are 2 answers

1
ron rothman On BEST ANSWER

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 name and age.

class Person(object):
    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)

print bob
print bob.age

Output:

<__main__.Person object at 0x1074e0bd0>
45
0
miindlek On

kwargs is a dictionary. So you should rather do this:

class Person(object):
    def __init__(self, **kwargs):
        self.name = kwargs["name"]
        self.age = kwargs["age"]