سؤال

I'm thinking about a situation where I have an object "Transaction", that has quite a few properties to it like account, amount, date, currency, type, etc.

I never plan to mutate these data points, and calculation logic will live in other classes. My question is, is it poor Python design to instantiate thousands of objects just to hold data? I find the data far easier to work with embedded in a class rather than trying to cram it into some combination of data structures.

هل كانت مفيدة؟

المحلول

No, this is perfectly fine. In fact, Python has support for it in the standard collections module:

from collections import namedtuple

Transaction = namedtuple("Transaction", ["account", "amount"])

instead of class Transaction(object): etc. Note that namedtuple is a kind of "class factory" and you need to pass it the name of the class to be constructed, as a string. That need not be the name you bind the result to, but doing so is still a good idea. Named tuple types are analogous to records in Pascal or structs in C: data holders with named members but no significant behavior of their own.

Usage:

>>> t = Transaction(account="my private account", amount=+1000)
>>> t
Transaction(account='my private account', amount=1000)
>>> t.amount
1000
>>> t.amount += 1
Traceback (most recent call last):
  File "<ipython-input-6-ae60188f2446>", line 1, in <module>
    t.amount += 1
AttributeError: can't set attribute

نصائح أخرى

I would say that all values are objects anyway. Let's say that instead of transaction class instance, you would have a dictionary {'transaction name':[123,'GBP','12/12/12',1234,'in']}. Now this dictionary is again an object and the difference is that it wasn't your own class. Everything is an object anyway. The fact that something is an object, does not automatically make it bulky, large, slow or whatever. Probably you would still need a consideration about these transactions of how many of those objects you want to keep in the memory in a given time?

It's matter of clear code design in my opinion. Lets say that now you have a class book which has a method of action, accepting transaction objects as an attribute. When this action method will then be using object properties, it would be much clearer than if it was referring to nth elements of a list for instance.

The fact that it's a class it also leaves you an opportunity to amend or add functionality in the future. For example you might want to add logging of all transaction, or withdraw method at some point.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top