Skip to content

Instantly share code, notes, and snippets.

@ychennay
Created March 17, 2020 21:11
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/d1aba3463359422aaada869de795914d to your computer and use it in GitHub Desktop.
Save ychennay/d1aba3463359422aaada869de795914d to your computer and use it in GitHub Desktop.
Example of data and non-data descriptors
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