Last active
March 21, 2020 02:25
-
-
Save ychennay/38347a3fe974b028b99cb0995964cead to your computer and use it in GitHub Desktop.
attributes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class NonNullStringDescriptor: | |
def __init__(self, value: str = "Default Name"): | |
self.value = value | |
def __get__(self, instance, owner): | |
print(f"__get__({self}, {instance}, {owner})") | |
return self.value | |
def __set__(self, instance, value): | |
print(f"__set__({self}, {instance}, {value})") | |
if isinstance(value, str) and len(value.strip()) > 0: | |
self.value = value | |
else: | |
raise TypeError("The value provided is not a non-null string.") | |
class Person: | |
name = NonNullStringDescriptor() # data descriptor for name | |
def __init__(self): | |
self.age = 22 | |
def __getattribute__(self, key): # always called on attribute lookup | |
print(f"__getattribute__({self}, {key})") | |
v = super(Person, self).__getattribute__(key) | |
print(f"Returned {v} from object.__getattribute__(...)") | |
return v | |
def __setattr__(self, key, value): | |
print(f"__setattr__({key}, {value})") | |
object.__setattr__(self, key, value) | |
def __getattr__(self, item): # fallback method | |
print(f"__getattr__ invoked.") | |
setattr(self, item, "Unknown") # Now item = Unknown | |
return "Unknown" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment