From ebc71de096cd2939af5b080562ddcd2c570e37c2 Mon Sep 17 00:00:00 2001 From: "xuanyi.wang" Date: Fri, 7 Apr 2023 00:03:36 +0200 Subject: [PATCH] Update page 'Day 5 homework - Sloetjes' --- Day 5 homework - Sloetjes.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Day 5 homework - Sloetjes.md diff --git a/Day 5 homework - Sloetjes.md b/Day 5 homework - Sloetjes.md new file mode 100644 index 0000000..ecc2375 --- /dev/null +++ b/Day 5 homework - Sloetjes.md @@ -0,0 +1,29 @@ +# Xuanyi Wang\_Day-5\_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. + + +``` +class Vault: + def __init__(self): + self._treasure = 'gold' + self._original_attrs = self.__dict__.copy() + + @property + def treasure(self): + if self.__dict__ != self._original_attrs: + print('Attribute deleted!') + 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' +``` \ No newline at end of file