Created
February 25, 2023 18:17
-
-
Save eivl/aec56fe1abc7ea0749bc87a82b5782ba to your computer and use it in GitHub Desktop.
Descriptor talk on python discord
This file contains hidden or 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
| ''' | |
| 1: Data descriptor | |
| 2: self.__dict__['d'] | |
| 3: non-data descriptor | |
| __slots__ | |
| __get_attr__ | |
| __get_attribute__ | |
| ''' | |
| from functools import wraps | |
| class Descriptor: | |
| def __init__(self): | |
| print('__init__') | |
| def __set_name__(self, owner, name): | |
| print('__set_name__') | |
| self.d_name = name | |
| def __set__(self, instance, value): | |
| print('__set__') | |
| setattr(instance, f'_{self.d_name}', value) | |
| def __delete__(self, instance): | |
| delattr(instance, f'_{self.d_name}') | |
| def __get__(self, instance, owner=None): | |
| print('__get__') | |
| return getattr(instance, f'_{self.d_name}', 42) | |
| class Foo: | |
| d = Descriptor() | |
| @property | |
| def foo(self): | |
| return 'hello' | |
| def __init__(self): | |
| self.__dict__['d'] = 11 | |
| f = Foo() | |
| class caced_property: | |
| def __init__(self, func): | |
| self.func = func | |
| self.name = func.__name__ | |
| def __set_name__(self, owner, name): | |
| self.name = name | |
| def __get__(self, instance, owner=None): | |
| if owner is None: | |
| return self | |
| retrieve = instance.__dict__[self.name] = self.func(instance) | |
| return retrieve | |
| class MyClass: | |
| @caced_property | |
| def foo(self): | |
| print('compute something important and timeconsuming') | |
| return 4242 | |
| class Circle: | |
| radius = 10 | |
| c = Circle | |
| c.radius = 11 | |
| c.radius | |
| ''' | |
| # code here | |
| # run your function here | |
| # some more code | |
| ''' | |
| def first_func(): | |
| print('This is my function') | |
| def second_func(): | |
| print('This is my second function') | |
| def custom_thing(func): | |
| def _func(): | |
| print('decorator before') | |
| func() | |
| print('decorator after') | |
| return _func | |
| custom_thing(first_func) | |
| custom_thing(second_func) | |
| @custom_thing | |
| def actual_function(): | |
| print('my actual function') | |
| actual_function = custom_thing(actual_function) | |
| actual_function() | |
| x = y = 0 | |
| def f(): | |
| x = y = 1 | |
| class C: | |
| print(x, y) | |
| x = 2 | |
| ''' | |
| x, y | |
| 0, 0 | |
| 0, 1 | |
| 1, 0 | |
| 1, 1 | |
| 2, 1 | |
| 2, 0 | |
| ''' | |
| f() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment