Created
May 5, 2017 21:10
-
-
Save o11c/72771bb834c9178cd4153371ea9617d1 to your computer and use it in GitHub Desktop.
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 via_data: | |
def __init__(self, name=None): | |
# name can be None for python 3.6 | |
self.name = name | |
def __get__(self, instance, owner): | |
if instance is not None: | |
assert self.name is not None, 'name not specified' | |
return instance.data[self.name] | |
return self | |
def __set_name__(self, owner, name): | |
# only called for python 3.6 | |
self.name = name | |
class Foo: | |
def __init__(self): | |
self.data = {} | |
self.data['x'] = 1 | |
self.data['y'] = 2 | |
self.data['z'] = 3 | |
x = via_data() | |
y = via_data() | |
z = via_data('z') | |
if __name__ == '__main__': | |
foo = Foo() | |
print('x', foo.x) | |
print('y', foo.y) | |
print('z', foo.z) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment