Reputation: 25
This may seem a weird question but the thing is that I have a class to which I want to assign a variable (so using self.vname = Whatever
in __init__
), but this variable name is passed as wkargs in the instantiation.
So the class looks like
class Object(object):
def __init__(self, **kwargs):
for key in kwargs.keys():
self.what_do_i_type_here = kwargs[key]
Actually this is a class which I will extend then so I am not sure how to do this.
I want to create a generic class which in each extension case will have different variables defined.
How to do so, or how to carry out a better approach?
Upvotes: 2
Views: 39
Reputation: 1774
I'm going to assume that you want the variable name to be the key.
You can use the setattr()
built-in function:
for key in kwargs:
setattr(self,key,kwargs[key])
Upvotes: 1
Reputation: 600026
You could use setattr
:
for key, value in kwargs.items()
setattr(self, key, value)
but I don't see the point, since you won't have any idea of the keys you've set so you won't be able to use them anywhere.
Why not keep them in a dictionary?
self.data = kwargs
then you can iterate through self.data
and its values whenever you like.
Upvotes: 3