aura
aura

Reputation: 543

Should a class to have several attributes or one attribute as dictionary with many keys, Python3

I have class for calculating temperatures of an object at different positions, based on ambient temperature. I have two ways of implementation. In BodyA, the temperature of each position is an attribute of the class; while in BodyB, there is an attribute pos_t, which is a dict, and the temperature of each position is just a key-value pair in the dict.

class BodyA:
    def __init__(self, ambient_temperature)
        self.amb_t = ambient_temperature
        self.pos1_t = self.amb_t + 1
        self.pos2_t = self.amb_t * 2
        self.pos3_t = self.pos1_t + self.pos2_t - 5


class BodyB:
    def __init__(self, ambient_temperature)
        self.amb_t = ambient_temperature
        self.pos_t = dict()
        self.pos_t['pos1'] = self.amb_t + 1
        self.pos_t['pos2'] = self.amb_t * 2
        self.pos_t['pos3'] = self.pos_t['pos1'] + self.pos_t['pos2'] - 5

In practical case, there are up-to 10 positions, and I want to build child-class from it. And some child-classes do not have certain positions. For example, pos2 can be missing in some child.

Could you please let me know, which design is better in terms of OOP and efficiency. Thanks.

Upvotes: 0

Views: 41

Answers (1)

progmatico
progmatico

Reputation: 4964

A data structure to store some custom identifiers that may or may exist calls clearly for a dict. As class attributes are also stored in an internal dict, the first approach can be used too, but to have pratical manipulation without explicit hand writing the members will require different code. I suspect performance will not matter. If you find it matters, maybe a redesign of the data structure that does not use classes at all will do, as object creation processing time may be relevant then.

Upvotes: 1

Related Questions