Home > Software engineering >  How to init a value in a class with a simple setting and getting attributes?
How to init a value in a class with a simple setting and getting attributes?

Time:09-30

The class I have been using looks simple, like this:

class Transaction(dict):
    __getattr__ = dict.get
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__

and then sending in:

transaction = Transaction({"to": "0x000", "from": "0x001": "timestamp": 1234})

and of course can be used like this transaction.to, however it looks like transaction.from does not work because from is a python reserved keyword

So I am curious using that simple class, is there a way to reassign from in the class to be something like

self.sender = dict.from

I have been trying with __init__ but with no luck

I also have written the class just with an __init__ and then assigning all values using self but with out a getter the class is not iterable

What I have been doing looks like this

# given data - {"to": "0x000", "from": "0x001": "timestamp": 1234}
item["sender"] = item["from"]
transaction = Transaction(item)

and then I have reference to it like transaction.sender.

CodePudding user response:

If I understand correctly, your end goal is to have a class that can be instantiated from a dict and expose the keys as attributes. I'm inferring that the dict can only contain certain keys since you're talking about mapping "from" to sender. In that case, I would do this completely differently: don't subclass dict, instead have an alternate constructor that can handle the dict. I'd keep a "normal" constructor mostly for the sake of the repr.

For example:

class Transaction:
    def __init__(self, to, from_, timestamp):
        self.to = to
        self.from_ = from_
        self.timestamp = timestamp

    @classmethod
    def from_dict(cls, d):
        return cls(d['to'], d['from'], d['timestamp'])

    def __repr__(self):
        """Show construction."""
        r = '{}({!r}, {!r}, {!r})'.format(
            type(self).__name__,
            self.to,
            self.from_,
            self.timestamp)
        return r

transaction = Transaction.from_dict({"to": "0x000", "from": "0x001", "timestamp": 1234})
print(transaction)  # -> Transaction('0x000', '0x001', 1234)
print(transaction.from_)  # -> 0x001

Here I'm using the trailing underscore convention covered in PEP 8:

  • single_trailing_underscore_: used by convention to avoid conflicts with Python keyword, e.g.

    tkinter.Toplevel(master, class_='ClassName')
    

By the way, if it's useful, the keyword module contains the names of all Python keywords.

  • Related