B
B
become_iron2017-01-05 00:18:30
Python
become_iron, 2017-01-05 00:18:30

What is the best way to create a dict-like class with a composite key?

The task is as follows:
1) there is a class that has 4 properties, 2 of which are "read-only"
2) you need to create a second class (some kind of dict-like), consisting of a sequence of instances of the first class and in which the composite should be used the key from the above two readonly properties
How to do it better?
I hope I explained more or less clearly
. I tried to do it by implementing the __eq__ and __hash__ methods for the first class, and in the second I stored instances of the first class in the set. Something like this: gist . But I don’t really like it: the creation of a set, of course, occurs according to a “composite key”, but you cannot get a value by this key I looked at the collections
library, but also did not look for a suitable

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
become_iron, 2017-01-10
@become_iron

It was decided like this:

class Trp:
    def __init__(self, prefix, name, value, comment):
        self.prefix = prefix  # readonly
        self.name = name  # readonly
        self.value = value
        self.comment = comment

class TrpStr:
    def __init__(self, *trps):
        self._trps = {}
        for trp in trps:
            self._trps.update({(trp.prefix, trp.name): trp})

The solution is certainly not ideal.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question