Skip to content

Instantly share code, notes, and snippets.

@spajak
Created June 11, 2019 17:05
Show Gist options
  • Save spajak/a35ba4e45ada2e95817b9d80cad4a996 to your computer and use it in GitHub Desktop.
Save spajak/a35ba4e45ada2e95817b9d80cad4a996 to your computer and use it in GitHub Desktop.
Simple usage of Python 3 descriptors
class MyDescriptor:
def __set_name__(self, owner, name):
self.name = name
def __get__(self, instance, owner):
return f'Surprise from "{self.name}" descriptor'
def __set__(self, instance, value):
# You can set any property here or raise an exception to make it read only property
pass
class Foo:
bar = MyDescriptor()
print(Foo.bar)
o = Foo()
print(o.bar)
'''
OUTPUT:
Surprise from "bar" descriptor
Surprise from "bar" descriptor
'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment