Python Forum
I would like to know more about dunders
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I would like to know more about dunders
#3
Ichabod801,

I use dunders quite a bit, but sometimes not sure which ones I need to provide.
For example. in the following code that I wrote, I wasn't sure if I needed to raise StopIteration or not, or if I needed
to include __repr__ Snippsat didn't think I did when I first posted this (pyforum.io):
from collections import namedtuple
import json


class Record:
    def __init__(self, fname=None):
        self.rec = self.read_data_file(fname)
        self.maxitem = len(self.rec)

    def read_data_file(self, fname):
        with open(fname, 'r') as f:
            j = f.read()
        return json.loads(j, object_hook=lambda data: namedtuple('data', data.keys())(*data.values()))

    def __repr__(self):
        return self

    def __iter__(self):
        self.itemnum = 0
        return self

    def __next__(self):
        if self.itemnum > self.maxitem:
            raise StopIteration
        rec = self.rec[self.itemnum]
        self.itemnum += 1
        return rec


if __name__ == '__main__':
    fname = 'StockData.json'
    r = Record(fname)
    for record in r:
        print(record)
There's a pretty good write up in the Fluent Python book which I have been reading, need to read more, so I
will just absorb what comes along. I usually learn at least something new from all that I read.

I took a quick look at your post, and it looks very interesting, I'll read it tomorrow morning as that's when my brain works best. Getting old sucks!

Larz60+
Reply


Messages In This Thread
RE: Tutorial Requests - by ichabod801 - Sep-30-2016, 02:46 PM
RE: Tutorial Requests - by Larz60+ - Oct-02-2016, 03:42 AM
RE: Tutorial Requests - by ichabod801 - Oct-04-2016, 12:44 AM
RE: Tutorial Requests - by nilamo - Oct-04-2016, 02:56 PM
RE: Tutorial Requests - by ichabod801 - Oct-04-2016, 09:40 PM
RE: Tutorial Requests - by Larz60+ - Oct-05-2016, 03:31 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020