What are the advantages and disadvantages of creating class and instance in this way in Python?
<pre><code>class CIFAR10Record(object):
    pass

result = CIFAR10Record()
result.height = 32
result.width = 32
result.depth = 3
</code></pre>

<p>This snippet of code creates a class and its instance.</p>

<p>What are the advantages and disadvantages of this pattern?</p>

<p>This code uses a class in order to "bunch together" a number of related fields.</p>

<p>The pros are that it's very flexible. The class is defined without any members. Any function can decide which fields to add. Different invocations can create objects of this class, and populate them in different ways (so, simultaneously, you could have objects of the same class with different members).</p>

<p>This flexibility is also a con. This lacks structure: it's harder to look at the code and decide which members the class will have. It's also less straightforward to get such an object, and iterate over the members. Finally, the class is an extreme case of no <a href="https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)" rel="nofollow">encapsulation</a>.</p>

<hr>

<p>Altogether, I think there are better alternatives:</p>

<p>If this flexibility is really needed (which is a question in itself), you might want to consider using a <code>dict</code> instead.</p>

<pre><code>result = {}
result['height'] = 32
result['width'] = 32
result['depth'] = 3
</code></pre>

<p>It's much clearer here (IMHO) that result is just a grouping of fields, and it's easier to iterate over the fields using <a href="https://docs.python.org/2/library/stdtypes.html#mapping-types-dict" rel="nofollow"><code>dict</code>'s methods</a>.</p>

<p>If this flexibility is not needed, and it's just a way to minimize the amount of code, you should consider using <a href="https://docs.python.org/2/library/collections.html#collections.namedtuple" rel="nofollow"><code>collections.namedtuple</code></a>.</p>

<pre><code>import collections

CIFAR10Record = collections.namedtuple('CIFAR10Record', ['height', 'width', 'depth'])
</code></pre>

python class