jiuses jiuses - 2 months ago 23
Python Question

What are the advantages and disadvantages of creating class and instance in this way in Python?

class CIFAR10Record(object):
pass

result = CIFAR10Record()
# Dimensions of the images in the CIFAR-10 dataset.
# See http://www.cs.toronto.edu/~kriz/cifar.html
# input format.
label_bytes = 1 # 2 for CIFAR-100
result.height = 32
result.width = 32
result.depth = 3


This snippet of codes created a class and it's instance.
What are the advantages and disadvantages of these?

Answer

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

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).

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 encapsulation.


Altogether, I think there are better alternatives:

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

result = {}
result['height'] = 32
result['width'] = 32
result['depth'] = 3

It's much clearer here (IMHO) that result is just a grouping of fields, and it's easier to iterate over the fields using dict's methods.

If this flexibility is not needed, and it's just a way to minimize the amount of code, you should consider using collections.namedtuple.

import collections

CIFAR10Record = collections.namedtuple('CIFAR10Record', ['height', 'width', 'depth'])
Comments