I’m trying to create an object in python which is composed of smaller objects. Each of the objects has its own meaning – each of the smaller objects and the entire object as a whole.
The problem is that I want each of the 3 objects to be seemingly independently addressable and to operate as standalone objects and this is rather difficult to achieve.
This problem would be easy to solve in C using pointers but I find it difficult to simulate this behavior in Python.
An example to the situation I’m talking about could be seen in a control word of a state machine: The control word (2 bytes) has a meaning as a whole and needs to be accesses (or transferred) as an object, but each of the bytes in the control word has its own meaning and needs to be set and accessed independently.
In C I’d do something like:
unsigned short control_word_memory;
unsigned short *control_word = &control_word_memory;
unsigned char *low_byte = &control_word_memory;
unsigned char *high_byte = low_byte + 1;
And thus I’d be able to access each of the elements easily and not be forced to maintain complex logic to keep all 3 objects in sync – an assignment into *control_word would update both low_byte and high_byte simultaneously, and any update to the byte objects will influence the control_word.
Is there a simple way to achieve this behavior in Python?
Two alternatives:
You can use C and a CPython wrapper… Or you can use properties:
now you can use it as:
given the further explanation from the comments:
you don’t need the dictionary at all, you can make our
Controlclass to behave like a dictionary implementing thedictprotocol (it has quite a few methods, you can leave out those that you are not using if you want):and then use it like this: