Skip to content

Instantly share code, notes, and snippets.

@iaindillingham
Created February 16, 2022 14:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iaindillingham/71aa6d207a0370d236520d4c313d7698 to your computer and use it in GitHub Desktop.
Save iaindillingham/71aa6d207a0370d236520d4c313d7698 to your computer and use it in GitHub Desktop.
Attribute Descriptors
import logging
logging.basicConfig(level=logging.INFO)
class LoggingProperty:
def __init__(self):
logging.info(f"Initializing '{self.__class__.__name__}'")
def __set_name__(self, owner, name):
logging.info(f"Setting '{self.__class__.__name__}.property_name' to '{name}'")
self.property_name = name
def __get__(self, instance, owner=None):
logging.info(f"Getting '{instance.__class__.__name__}.{self.property_name}'")
return instance.__dict__[self.property_name]
def __set__(self, instance, value):
logging.info(
f"Setting '{instance.__class__.__name__}.{self.property_name}' to '{value}'"
)
instance.__dict__[self.property_name] = value
class Person:
first_name = LoggingProperty()
def __init__(self, first_name):
cls_name = type(self).__name__
logging.info(f"Initializing '{self.__class__.__name__}'")
self.first_name = first_name
person = Person("John")
person.first_name
# INFO:root:Initializing 'LoggingProperty'
# INFO:root:Setting 'LoggingProperty.property_name' to 'first_name'
# INFO:root:Initializing 'Person'
# INFO:root:Setting 'Person.first_name' to 'John'
# INFO:root:Getting 'Person.first_name'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment