From 3ee56351ae5187242ad0f24905a3b595ca744964 Mon Sep 17 00:00:00 2001 From: "xuanyi.wang" Date: Wed, 12 Apr 2023 00:47:54 +0200 Subject: [PATCH] Update page 'Day 5 homework - Sloetjes' --- Day 5 homework - Sloetjes.md | 49 ++++++++++++++++++++++++++---------- 1 file changed, 36 insertions(+), 13 deletions(-) diff --git a/Day 5 homework - Sloetjes.md b/Day 5 homework - Sloetjes.md index 89a2b3d..7064544 100644 --- a/Day 5 homework - Sloetjes.md +++ b/Day 5 homework - Sloetjes.md @@ -1,4 +1,4 @@ -# Xuanyi Wang\_Day-5\_Homework\_04/05/23 +# Xuanyi Wang\_Day-5&6\_Homework\_04/05/23 **The assignment for tonight is to write a class named Vault containing an attribute named "treasure" which returns "gold" under normal circumstances, but a warning message such as "attribute deleted!" if it detects any of its attributes have been changed. You can use the descriptor protocol (set, etc) to detect if its attributes have been changed, and it will have to check its own dict against a known good copy before accessing the treasure attribute to make sure that the attributes are what they're supposed to be.** @@ -7,25 +7,48 @@ class Vault: def __init__(self): self._treasure = 'gold' - self._original_attrs = self.__dict__.copy() + self._dict_copy = self.__dict__.copy() + + def __setattr__(self, name, value): + if name != '_dict_copy' and name != '_treasure': + if self.__dict__ != self._dict_copy: + print("attribute deleted!") + self._dict_copy = self.__dict__.copy() + super().__setattr__(name, value) @property def treasure(self): - if self.__dict__ != self._original_attrs: - print('Attribute deleted!') + if self.__dict__ != self._dict_copy: + print("attribute deleted!") + self._dict_copy = self.__dict__.copy() return self._treasure - - def __setattr__(self, key, value): - self.__dict__[key] = value - if key != '_original_attrs' and self.__dict__ != self._original_attrs: - print('Attribute deleted!') ``` ##### An example usage of the `Vault` class: ``` -v = Vault() -print(v.treasure) # prints 'gold' -v.x = 10 -print(v.treasure) # prints 'Attribute deleted!\ngold' +vault = Vault() +print(vault.treasure) +``` +##### Output: +``` +attribute deleted! +gold +``` +##### change an attribute of the vault instance +``` +vault._key = 'silver' +``` +##### Output: +``` +attribute deleted! +``` +##### Try to access the treasure attribute again +``` +print(vault.treasure) +``` +##### Output: +``` +attribute deleted! +gold ``` **To get the other person's class to return "gold", despite any countermeasures they've implemented:**