I'm trying to use **kwargs
to create a dictionary inside an instance of a class. I want to hand my Book class two required variables(title
and author
) as well as a number of optional key/value pairs, and have it create an internal dictionary holding those keys and values. Here is my code:
class Book:
def __init__(self, title, author, **kwargs):
self.info = {
'title': title,
'author': author,
}
For example, I'd like to hand Book an argument like year='1961'
and have it set up a key/value pair ('year': '1961'
). Up until now I've been using if/else
statements for this, but that seems inefficient and ugly. Can I use **kwargs
to do it?