Python @ DjangoSpin

Object Oriented Python: Storing keyword arguments dynamically

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Storing keyword arguments dynamically in Python

Storing keyword arguments dynamically in Python

We can utilize the builtin dictionary of keyword arguments of each object (stored in __dict__ attribute of the object) to store the keyword arguments supplied to it during its creation.

>>> class Person(object):
    def __init__(self, **kwargs):
        for argument in kwargs.keys():
            self.__setattr__(argument, kwargs[argument])
 
             
>>> ethan = Person(name = 'Ethan', age = 23, height = 170)
>>> ethan.__dict__
{'age': 23, 'name': 'Ethan', 'height': 170}

See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply