The built-in object
can be instantiated but can't have any attributes set on it. (I wish it could, for this exact purpose.) This is because it doesn't have a __dict__
to hold the attributes.
I generally just do this:
class Object(object):
pass
obj = Object()
obj.somefield = "somevalue"
But consider giving the Object
class a more meaningful name, depending on what data it holds.
Another possibility is to use a sub-class of dict
that allows attribute access to get at the keys:
class AttrDict(dict):
def __getattr__(self, key):
return self[key]
def __setattr__(self, key, value):
self[key] = value
obj = AttrDict()
obj.somefield = "somevalue"
To instantiate the object attributes using a dictionary:
d = {"a": 1, "b": 2, "c": 3}
for k, v in d.items():
setattr(obj, k, v)
a = object()
and you needobj.a = object()
. Again I am talking about the example, in your actual code an object inside an object might be useful. – Mistakable