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)
Answer from FogleBird on Stack OverflowThe 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)
You could use my ancient Bunch recipe, but if you don't want to make a "bunch class", a very simple one already exists in Python -- all functions can have arbitrary attributes (including lambda functions). So, the following works:
obj = lambda: None
obj.somefield = 'somevalue'
Whether the loss of clarity compared to the venerable Bunch recipe is OK, is a style decision I will of course leave up to you.
Shortest way of creating an object with arbitrary attributes in Python? - Stack Overflow
Working with objects with many attributes - best approach?
Can an object be an attribute of another object?
dynamically add properties to a class (property, __getattribute__, something else?)
Properties must be defined on the class, not the instance. You're assigning the property on self when it needs to be assigned on A.
But dynamically creating attributes like this is weird and messy. The first thing you should do is reconsider whether you really do need to dynamically create attributes. It's an overly complex solution to most problems. Describing your problem to us might be helpful here. If you still decide you need this then you should use __getattr__ (and probably not __getattribute__). Properties are not the right solution.
How do you create an object in Python?
What does it mean to create an object in Python?
What is an object in Python 3?
type('', (), {})() will create an object that can have arbitrary attributes.
Example:
obj = type('', (), {})()
obj.hello = "hello"
obj.world = "world"
print obj.hello, obj.world # will print "hello world"
type() with three arguments creates a new type.
The first argument
''is the name of the new type. We don't care about the name, so we leave it empty.The second argument
()is a tuple of base types. Hereobjectis implicit.The third argument is a dictionary of attributes of the new object. We start off with no attributes so it's empty
{}.
In the end we instantiate a new instance of this new type with ().
The original code can be streamlined a little by using __dict__:
In [1]: class data:
...: def __init__(self, **kwargs):
...: self.__dict__.update(kwargs)
...:
In [2]: d = data(foo=1, bar=2)
In [3]: d.foo
Out[3]: 1
In [4]: d.bar
Out[4]: 2
In Python 3.3 and greater, this syntax is made available by the types.SimpleNamespace class.
I'm working on my own version of thegamesdb api for python and I'm having an internal struggle over the best way to handle multiple sub-elements for items. For example, when you call the GetPlatform API, each platform object can have many elements. I want to create a platform object that contains all of those attributes, but I'm not sure if I should create a new Platform object within the XML parsing method and then modify the object as I read the items, read all the items first into variables and call the Platform object with a dozen or more arguments, pass a dictionary to the Platform object and parse it within init, or maybe even another idea I've yet to think of.
My current strategy is to create a new Platform object with just the id and name, then use the setattr() method on the object as I iterate over the elements, but I'm not sure if this is pythonic or not.
Any suggestions or resources on how this could should be properly written?
Github link