Update page 'Day 5 and 6 homework - Sloetjes'
@@ -33,7 +33,7 @@ print(vault.treasure)
|
|||||||
attribute deleted!
|
attribute deleted!
|
||||||
gold
|
gold
|
||||||
```
|
```
|
||||||
##### change an attribute of the vault instance
|
##### Change an attribute of the vault instance
|
||||||
```
|
```
|
||||||
vault.key = 'silver'
|
vault.key = 'silver'
|
||||||
```
|
```
|
||||||
@@ -50,7 +50,46 @@ print(vault.treasure)
|
|||||||
attribute deleted!
|
attribute deleted!
|
||||||
gold
|
gold
|
||||||
```
|
```
|
||||||
|
##### Another way to implement Vault:
|
||||||
|
```
|
||||||
|
class Vault:
|
||||||
|
def __init__(self):
|
||||||
|
self._known_attrs = {'treasure': 'gold'}
|
||||||
|
self._attrs = self._known_attrs.copy()
|
||||||
|
|
||||||
|
def __getattribute__(self, name):
|
||||||
|
if name == 'treasure':
|
||||||
|
attrs = object.__getattribute__(self, '_attrs')
|
||||||
|
known_attrs = object.__getattribute__(self, '_known_attrs')
|
||||||
|
if attrs != known_attrs:
|
||||||
|
print('attribute deleted!')
|
||||||
|
return attrs[name]
|
||||||
|
return object.__getattribute__(self, name)
|
||||||
|
|
||||||
|
def __setattr__(self, name, value):
|
||||||
|
if name == 'treasure':
|
||||||
|
attrs = object.__getattribute__(self, '_attrs')
|
||||||
|
attrs[name] = value
|
||||||
|
known_attrs = object.__getattribute__(self, '_known_attrs')
|
||||||
|
if attrs != known_attrs:
|
||||||
|
print('attribute deleted!')
|
||||||
|
else:
|
||||||
|
object.__setattr__(self, name, value)
|
||||||
|
vault = Vault()
|
||||||
|
print(vault.treasure)
|
||||||
|
```
|
||||||
|
###### Output:
|
||||||
|
```
|
||||||
|
gold
|
||||||
|
```
|
||||||
|
##### Change an attribute of the vault instance
|
||||||
|
```
|
||||||
|
vault.treasure = 'silver'
|
||||||
|
```
|
||||||
|
###### Output:
|
||||||
|
```
|
||||||
|
attribute deleted!
|
||||||
|
```
|
||||||
**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:**
|
||||||
###### It can be achieved by creating a new class that inherits from the `Vault` class and overrides its `_treasure` attribute.
|
###### It can be achieved by creating a new class that inherits from the `Vault` class and overrides its `_treasure` attribute.
|
||||||
```
|
```
|
||||||
|
|||||||
Reference in New Issue
Block a user