Created
June 11, 2019 17:05
-
-
Save spajak/a35ba4e45ada2e95817b9d80cad4a996 to your computer and use it in GitHub Desktop.
Simple usage of Python 3 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 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