forked from SVIG/python-bootcamp
51 lines
1.5 KiB
Python
51 lines
1.5 KiB
Python
|
|||
|
|
class Vault:
|
||
|
|
def __init__(self):
|
||
|
|
self._treasure = "gold"
|
||
|
|
self._known_good_copy = self.__dict__.copy()
|
||
|
|
|
||
|
|
def __getattribute__(self, name):
|
||
|
|
if name == "treasure":
|
||
|
|
if self.__dict__ != self._known_good_copy:
|
||
|
|
print("Attribute deleted!")
|
||
|
|
return self._treasure
|
||
|
|
else:
|
||
|
|
return object.__getattribute__(self, name)
|
||
|
|
|
||
|
|
def __setattr__(self, name, value):
|
||
|
|
if name != "_treasure" and name != "_known_good_copy":
|
||
|
|
print("Attribute deletion detected!")
|
||
|
|
self._known_good_copy = self.__dict__.copy()
|
||
|
|
object.__setattr__(self, name, value)
|
||
|
|
v = Vault()
|
||
|
|
Vault.treasure = " haha monkeypatched"
|
||
|
|
print(v.treasure)
|
||
|
|
|
||
|
|
'''
|
||
|
|
class Vault:
|
||
|
|
def __init__(self):
|
||
|
|
self._treasure = "gold"
|
||
|
|
self._known_good_copy = self.__dict__.copy()
|
||
|
|
|
||
|
|
def __get__(self, instance, owner):
|
||
|
|
if instance is None:
|
||
|
|
return self
|
||
|
|
else:
|
||
|
|
if instance.__dict__ != self._known_good_copy:
|
||
|
|
print("Attribute deleted!")
|
||
|
|
return self._treasure
|
||
|
|
|
||
|
|
def __set__(self, instance, value):
|
||
|
|
print("Attribute deletion detected!")
|
||
|
|
self._known_good_copy = instance.__dict__.copy()
|
||
|
|
|
||
|
|
def __delete__(self, instance):
|
||
|
|
print("Attribute deletion detected!")
|
||
|
|
self._known_good_copy = instance.__dict__.copy()
|
||
|
|
|
||
|
|
def __set_name__(self, owner, name):
|
||
|
|
self.name = name
|
||
|
|
v = Vault()
|
||
|
|
Vault._treasure = " haha monkeypatched"
|
||
|
|
print(v._treasure)
|
||
|
|
'''
|