קורס Advanced Python3 שיעור תרגול מתודות מיוחדות


זה נושא דיון מלווה לערך המקורי ב- https://www.tocode.co.il/bundles/advanced-python3/lessons/magic-methods-lab

import json
class AddressBook:
    def __init__(self, filename):
        self.filename = filename
        self.fp = None
        self.contacts = None

    def __enter__(self):
        
        print("__enter__")
        try:
            self.fp = open(self.filename, "r")
        except FileNotFoundError as e:
            self.fp = open(self.filename, "x")
            self.fp.close()
            self.fp = open(self.filename, "r")

        try:
            data = json.load(self.fp)
            self.contacts = data['contacts']
        except Exception as e:
            self.contacts = {}
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("__exit__")
        if exc_type is None:
            with open(self.filename, 'w') as outfile:
                json.dump({"contacts": self.contacts}, outfile)
                self.fp.close()
        else:
            self.fp.close()
            raise IndexError

    def add(self, name, email):
        self.contacts[name] = email
        # To simulate raising exception
        # raise IndexError("testing")

    def email(self, name):
        return self.contacts[name]

    def __setitem__(self, name, email):
        self.contacts[name] = email

    def __getitem__(self, name):
        return self.contacts[name]

    def __str__(self):
        with open(self.filename) as json_file:
            try:
                data = json.load(json_file)
            except Exception as e:
                pass
            contacts = data['contacts']
            return json.dumps(contacts)
with AddressBook('contacts.json') as ab:
    ab.add('Eve', 'eve@gmail.com')
    ab.add('Alice', 'alice@walla.co.il')

print(ab)

with AddressBook('contacts.json') as ab:
    print(ab.email('Eve'))

with AddressBook('contacts.json') as ab:
    ab['Dan'] = 'dan@gmail.com'

with AddressBook('contacts.json') as ab:
    print(ab['Dan'])

הי,
לא לגמרי הבנתי למה אתה מתעקש ליצור קובץ אם הוא לא קיים ב enter. יכול להיות שאי אפשר ליצור את הקובץ כי אין לך הרשאות או שמישהו הכניס שם קובץ לא תקין.

יכול גם להיות שאחרי שתיצור את הקובץ כשתגיע ל exit תגלה שאתה לא יכול לכתוב אליו כי דברים השתנו מאז ה enter או שפתאום אין לך הרשאות כתיבה.

אני חושב שכדאי:

  1. ב enter לא לנסות ליצור קובץ אלא רק לנסות לפתוח את הקיים. אם לא קיים לשמור מבנה נתונים ריק על self.

  2. ב exit אם לא מצליח לשמור לזרוק Exception כדי שקוד חיצוני יוכל לטפל במצב שהמידע לא נשמר (את זה אני חושב שהקוד הנוכחי שלך כבר עושה)

תיקנתי

def __enter__(self):
                print("__enter__")
        try:
            self.fp = open(self.filename, "r")
            data = json.load(self.fp)
            self.contacts = data['contacts']
        except Exception as e:
            self.contacts = {}

        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("__exit__")
        try:
            self.fp.close()
        except Exception:
            pass

        if exc_type is None:
            with open(self.filename, 'w') as outfile:
                json.dump({"contacts": self.contacts}, outfile)
        else:
            raise IndexError
לייק 1

אגב בשביל להדביק קוד כאן משתמשים באותו כתיב של דיסקורד עם השלושה סימני גרש הפוך