Update page 'Day 5 homework - Sloetjes'
@@ -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'
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user