Suponiendo que tengo una clase que se define con variables de la siguiente manera:
import numpy as np
class DataShell:
dS=''
name=''
type=''
some other variables
Inicializo un objeto
Obj=DataShell()
Tengo un diccionario L y quiero asignar los valores del diccionario a las variables de clase del objeto.
{'name': 'abc', 'type': 'def', 'dS': 'hij'}
Estoy probando el siguiente código para hacer esto:
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])
Esto es crear una nueva variable en mi objeto llamada 'el'
y asignarle un valor en lugar de cambiar mi Obj.name
, Obj.dS
o Obj.type
3 respuestas
Puede usar setattr
y hasattr
. Por ejemplo:
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
¿Por qué no hacer una función de inicialización que tome los valores?
class DataShell:
def __init__(self, dS='', name='', type=''):
dS = dS
name = name
type = type
Luego use:
DataShell(**L)
O incluso más fácil en Python 3 use dataclass
import dataclass
@dataclass
class DataShell:
dS: str = ''
name: str = ''
type: str = ''
Obj = DataShell(**L)
El código que copió en la pregunta no funciona en absoluto. Traté de modificar su código y ahora está funcionando.
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
para establecer dinámicamente los atributos de clase
Preguntas relacionadas
Nuevas preguntas
python
Python es un lenguaje de programación multipropósito, de tipificación dinámica y de múltiples paradigmas. Está diseñado para ser rápido de aprender, comprender y usar, y hacer cumplir una sintaxis limpia y uniforme. Tenga en cuenta que Python 2 está oficialmente fuera de soporte a partir del 01-01-2020. Aún así, para preguntas de Python específicas de la versión, agregue la etiqueta [python-2.7] o [python-3.x]. Cuando utilice una variante de Python (por ejemplo, Jython, PyPy) o una biblioteca (por ejemplo, Pandas y NumPy), inclúyala en las etiquetas.