Skip to content

Instantly share code, notes, and snippets.

@ychennay
Created March 17, 2020 21:15
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 ychennay/895c580d5d3cccd7af2df2ba7433a613 to your computer and use it in GitHub Desktop.
Save ychennay/895c580d5d3cccd7af2df2ba7433a613 to your computer and use it in GitHub Desktop.
Example of a Python class using descriptors as properties
class Student:
def __init__(self):
print(f"\n__init__ called on Student.")
def __getattribute__(self, key):
print(f"\n__getattribute__ invoked on Student with key {key}")
v = super(Student, self).__getattribute__(key)
if hasattr(v, '__get__'):
print(f"\n{v} has a __get__ method")
return v.__get__(None, self)
return v
print("\nname property of Student being prepared.")
name = NameDescriptor() # note that the property is defined as part of the Student class, not instance
print("\ngrade property of Student being prepared.")
grade = GradeDescriptor()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment