jiuses
jiuses

Reputation: 55

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

class CIFAR10Record(object):
    pass

result = CIFAR10Record()
result.height = 32
result.width = 32
result.depth = 3

This snippet of code creates a class and its instance.

What are the advantages and disadvantages of this pattern?

Upvotes: 2

Views: 2276

Answers (1)

Ami Tavory
Ami Tavory

Reputation: 76297

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'])

Upvotes: 4

Related Questions