Created
March 17, 2020 21:11
-
-
Save ychennay/d1aba3463359422aaada869de795914d to your computer and use it in GitHub Desktop.
Example of data and non-data descriptors
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 NameDescriptor: | |
""" | |
NameDescriptor is a data descriptor because it implements __get__ and one of either __set__ or __del__ | |
""" | |
def __init__(self, name='Any Name'): | |
print(f"\n__init__ called on NameDescriptor.") | |
self.name: str = name | |
def __get__(self, instance, klass) -> str: | |
print(f"\n__get__ called on NameDescriptor. Instance is {instance}. Class type is {klass}") | |
return self.name | |
def __set__(self, instance, name): | |
print(f"\n__set__ called on NameDescriptor with value of {name}. Instance is {instance}.") | |
if isinstance(name, str): | |
self.name = name | |
else: | |
raise TypeError("Must pass in a string.") | |
class GradeDescriptor: | |
""" | |
NameDescriptor is a non-data descriptor because it implements only a __get__ method | |
""" | |
def __init__(self, grade: int = 10): | |
print("\n__init__ called on GradeDescriptor.") | |
self.grade = grade | |
def __get__(self, instance, klass): | |
print(f"\n__get__ called on GradeDescriptor. Instance is {instance}. Class type is {klass}") | |
return self.grade |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment