Built-in decorators for methods

As you might have known from looking at the official documentation (PYDESCR-02), all @property, @classmethod, and @staticmethod decorators are descriptors.

We have mentioned several times that the idiom makes the descriptor return itself when it's being called from a class directly. Since properties are actually descriptors, that is the reason why, when we ask it from the class, we don't get the result of computing the property, but the entire property object instead:

>>> class MyClass:
... @property
... def prop(self): pass
...
>>> MyClass.prop
<property object at 0x...>

For class methods, the __get__ function in the descriptor will make sure that the class is the first parameter to be passed to the function being decorated, regardless of whether it's called from the class directly or from an instance. For static methods, it will make sure that no parameters are bound other than those defined by the function, namely undoing the binding done by __get__() on functions that make self the first parameter of that function.

Let's take an example; we create a @classproperty decorator that works as the regular @property decorator, but for classes instead. With a decorator like this one, the following code should be able to work:

class TableEvent:
schema = "public"
table = "user"

@classproperty
def topic(cls):
prefix = read_prefix_from_config()
return f"{prefix}{cls.schema}.{cls.table}"


>>> TableEvent.topic
'public.user'

>>> TableEvent().topic
'public.user'

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.187.199