Diferències
Ací es mostren les diferències entre la revisió seleccionada i la versió actual de la pàgina.
Ambdós costats versió prèvia Revisió prèvia | |||
development:python:decorators [12/09/2024 03:54] – mate | development:python:decorators [15/09/2024 23:48] (actual) – [Decorador con parámetros mediante clases] mate | ||
---|---|---|---|
Línia 126: | Línia 126: | ||
# en decorador despues de wrapee foo de fa fa | # en decorador despues de wrapee foo de fa fa | ||
</ | </ | ||
+ | |||
+ | == Ejemplo decoración con clases | ||
+ | <code python> | ||
+ | # | ||
+ | # -*- coding: utf-8 -*- | ||
+ | |||
+ | from types import MethodType | ||
+ | |||
+ | class Decorator(): | ||
+ | def __init__(self, | ||
+ | print(f" | ||
+ | self.func = func | ||
+ | |||
+ | def __call__(self, | ||
+ | print(" | ||
+ | print(nom_funcio := self.func.__name__) | ||
+ | print(B.classvar) | ||
+ | |||
+ | retorn = self.func(*args, | ||
+ | print(" | ||
+ | |||
+ | return retorn | ||
+ | | ||
+ | def __get__(self, | ||
+ | # Retorna un método si se llama en una instancia | ||
+ | return self if instance is None else MethodType(self, | ||
+ | |||
+ | |||
+ | class Decorator2(): | ||
+ | def __init__(self, | ||
+ | print(f" | ||
+ | self.func = func | ||
+ | |||
+ | def __call__(self): | ||
+ | print(" | ||
+ | print(self.func.__name__) | ||
+ | print(B.classvar) | ||
+ | |||
+ | self.func(self) | ||
+ | print(" | ||
+ | |||
+ | |||
+ | class A(): | ||
+ | @staticmethod | ||
+ | def decorator(func): | ||
+ | def wrapper(*args, | ||
+ | print(" | ||
+ | |||
+ | print(nom_funcio := func.__name__) | ||
+ | print(B.classvar) | ||
+ | |||
+ | retorn = func(*args, | ||
+ | print(" | ||
+ | |||
+ | return retorn | ||
+ | |||
+ | |||
+ | return wrapper | ||
+ | |||
+ | |||
+ | class B(A): | ||
+ | classvar = None | ||
+ | |||
+ | def __init__(self, | ||
+ | self.var = var | ||
+ | B.classvar = var | ||
+ | |||
+ | def decorator(func): | ||
+ | def wrapper(*args, | ||
+ | print(" | ||
+ | | ||
+ | print(nom_funcio := func.__name__) | ||
+ | print(B.classvar) | ||
+ | |||
+ | retorn = func(*args, | ||
+ | | ||
+ | print(" | ||
+ | |||
+ | return retorn | ||
+ | | ||
+ | |||
+ | return wrapper | ||
+ | |||
+ | @Decorator | ||
+ | def run(self, | ||
+ | print(f" | ||
+ | |||
+ | @Decorator2 | ||
+ | def run2(self, | ||
+ | print(f" | ||
+ | | ||
+ | @A.decorator | ||
+ | def run3(self, | ||
+ | print(f" | ||
+ | |||
+ | @decorator | ||
+ | def run4(self, | ||
+ | print(f" | ||
+ | |||
+ | |||
+ | o = B(' | ||
+ | o.run() | ||
+ | o.run2() | ||
+ | o.run3() | ||
+ | o.run4() | ||
+ | print(o.__dict__) | ||
+ | </ | ||
+ | * '' | ||