Update page 'Day 5 homework - Sloetjes'

xuanyi.wang
2023-04-12 00:47:54 +02:00
parent 998caa3678
commit 3ee56351ae
+36 -13
@@ -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.** **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: class Vault:
def __init__(self): def __init__(self):
self._treasure = 'gold' 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 @property
def treasure(self): def treasure(self):
if self.__dict__ != self._original_attrs: if self.__dict__ != self._dict_copy:
print('Attribute deleted!') print("attribute deleted!")
self._dict_copy = self.__dict__.copy()
return self._treasure 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: ##### An example usage of the `Vault` class:
``` ```
v = Vault() vault = Vault()
print(v.treasure) # prints 'gold' print(vault.treasure)
v.x = 10 ```
print(v.treasure) # prints 'Attribute deleted!\ngold' ##### 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:** **To get the other person's class to return "gold", despite any countermeasures they've implemented:**