Objects without behavior

I’m thinking about a situation where I have a Transaction object that has many properties, such as account, amount, date, currency, type, etc.

I never plan to mutate these data points, and the calculation logic will live in other classes. My question is: is the Python project inconvenient to create thousands of objects to store data? I find it much easier to work with data embedded in a class, rather than trying to squeeze it into some combination of data structures.

+7
source share
2 answers

No, that's fine. In fact, Python supports 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 “factory class” and you need to pass it the name of the class to be created as a string. It should not be the name to which you attach the result, but it is still a good idea. Named types of tuples are similar to entries in Pascal or structures in C holders: with named members, but have no significant behavior.

Using:

 >>> 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 
+8
source

I would say that all values ​​are objects anyway. Say that instead of an instance of a transaction class, you will have the dictionary {'transaction name': [123, 'GBP', '12 / 12/12 ', 1234,' in ']}. Now this dictionary is again an object, and the difference is that it was not your own class. Anyway, an object. The fact that something is an object does not automatically make it bulky, large, slow, or any other. You probably still need to account for these transactions, how many of these objects do you want to keep in memory at a given time?

In my opinion, this is a matter of clear code design. Suppose you now have a cool book that has an action method that accepts transaction objects as an attribute. When this action method uses the properties of an object, it will be much clearer than if it referred to the nth elements of the list, for example.

The fact that this is a class also leaves you with the ability to change or add functionality in the future. For example, you can add the registration of the entire transaction or remove the method at some point.

+1
source

All Articles