Created
March 17, 2020 21:15
-
-
Save ychennay/895c580d5d3cccd7af2df2ba7433a613 to your computer and use it in GitHub Desktop.
Example of a Python class using descriptors as properties
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 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