3

I try to ad-hoc build up an object, something like:

b = object()
b.a = 0

But no, I can not add an a to object b. It's explained here, why that happens. Mainly because object does not have a dict.

But, is there a correct way to ad-hoc construct such an object b? Maybe instead of object a class that can take properties?

(Before you warn me or advise me to just build a class - yes, I'm aware that this might be the best way to do in many cases. But first, I think, there are cases where an ad-hoc object is useful, maybe just for lazyness in a small code. Second, I also want to understand what's behind the two cases a and b.)

Community
  • 1
  • 1
Michael
  • 7,407
  • 8
  • 41
  • 84
  • Keep in mind that's the initializer, not the constructor. – miradulo Apr 20 '16 at 07:25
  • I don't know the details, but there is definitely a bit more happening when you make something a `class`, including adding `__dict__` attribute (note: Python uses the term attribute instead of property; properties are a special type of attribute). Quote from the documentation: [Note: object does not have a __dict__, so you can’t assign arbitrary attributes to an instance of the object class.](https://docs.python.org/3/library/functions.html#object). –  Apr 20 '16 at 07:46
  • As for an (ugly) one-liner that doesn't use `class`, to quickly create a simple object: `b = type('MyClass', (object,), {})()`. –  Apr 20 '16 at 07:50
  • So...stuck in the old Stack Overflow problem: Question gets closed within minutes, but no one will ever re-open it, even though the problem was completely fixed. What should I do? – Michael Apr 20 '16 at 11:19

0 Answers0