Reputation: 596
Assuming I have a class which is defined with variables as follows:
import numpy as np
class DataShell:
dS=''
name=''
type=''
some other variables
I initialize an object
Obj=DataShell()
I have a dictionary L and I want to assign the values from the dictionary to the class variables of the object
{'name': 'abc', 'type': 'def', 'dS': 'hij'}
I am trying out the following code to do this:
attributes = [attr for attr in dir(Obj)
if not attr.startswith('__')]
for key in L:
for el in attributes:
if key==el:
Obj.el=str(L[key])
This is creating a new variable in my object called 'el'
and assigning a value to it instead of changing my Obj.name
, Obj.dS
or Obj.type
Upvotes: 0
Views: 472
Reputation: 27485
Why not make an initialization function that takes the values?
class DataShell:
def __init__(self, dS='', name='', type=''):
dS = dS
name = name
type = type
Then use:
DataShell(**L)
Or even easier in Python 3 use dataclass
import dataclass
@dataclass
class DataShell:
dS: str = ''
name: str = ''
type: str = ''
Obj = DataShell(**L)
Upvotes: 4
Reputation: 3114
The code you copied in the question is not at all working. I tried to modify your code and now it is working -
class DataShell:
dS=''
name=''
type=''
Obj=DataShell()
print(id(Obj))
L = {'name': 'abc', 'type': 'def', 'dS': 'hij'}
attributes = [attr for attr in dir(Obj)
if not attr.startswith('__')]
print(attributes)
for key in L:
for el in attributes:
if key==el:
if hasattr(Obj, el):
setattr(Obj, el, L[key])
print(id(Obj))
print(dir(Obj))
print(Obj.dS)
print(Obj.name)
print(Obj.type)
use setattr
for dynamically setting the class attributes
Upvotes: 1
Reputation: 3494
You can use setattr
and hasattr
. For example:
class MyClass(object):
attr1 = 1
attr2 = 2
myobject = MyClass()
m = {'attr1': 19, 'some_other_name': 'blah'}
for name, value in m.items():
if hasattr(myobject, name):
setattr(myobject, name, value)
print(myobject.attr1) # 19
Upvotes: 4