user308827
user308827

Reputation: 21961

Grouping together class members in python

class CFT(object):
        self.c3prarea = numpy.zeros(shape=(5, 5))
        self.c4prarea = numpy.zeros(shape=(5, 5))
        self.c5prarea = numpy.zeros(shape=(5, 5))

In the class above, I would like to group the 3 members together so that I can iterate over them. What is the best way:

  1. Create a list: ll = [self.c3prarea, self.c4prarea, self.c5prarea]

or,

  1. Create an enum

or,

  1. Some other method?

--EDIT based on @9000's soln below, an attempt at using named tuples:

self.CFT_names = collections.namedtuple('CFT_names', 'c3prarea c4prarea c5prarea')

self.c3prarea = numpy.zeros(shape=(5, 5))

Upvotes: 0

Views: 41

Answers (1)

9000
9000

Reputation: 40894

I'd use a tuple:

class Foo(object):
  def __init__(self):
    self.bars = (numpy.zeros(shape=(5, 5)),...)  # however many you need

Why a tuple:

  • It's immutable, you can't remove or add a member by mistake.
  • It's easy to iterate over, or use index access.
  • If you need names in the future, you can transparently upgrade to namedtuple.

Also, chances are that this 3-tuple may be a simple class by itself, with its own methods that do not depend on other parts of the original CTF class. If so, it's worth factoring out; you could use tupledirectly as a base class.

Upvotes: 1

Related Questions