“Utilisation des décorateurs” Réponses codées

# décorateur

# decorator function
def outer(func):
    def inner():
        str1 = func() 
        return str1.upper() # addition of functionality
    return inner

@outer 
def print_str():
    return "good morning"

print(print_str())

# Output -> 'GOOD MORNING'
# A decorator is a function that takes another function as an argument, adds some kind of functionality to it and returns another function. Python decorators help add functionality to an existing code(function) which may aid in code reusability. 
Impossible Impala

Utilisation des décorateurs

class ClassHolder:
    def __init__(self):
        self.classes = {}

    def add_class(self, c):
        self.classes[c.__name__] = c

    # -- the decorator
    def held(self, c):
        self.add_class(c)

        # Decorators have to return the function/class passed (or a modified variant thereof), however I'd rather do this separately than retroactively change add_class, so.
        # "held" is more succint, anyway.
        return c 

    def __getitem__(self, n):
        return self.classes[n]

food_types = ClassHolder()

@food_types.held
class bacon:
    taste = "salty"

@food_types.held
class chocolate:
    taste = "sweet"

@food_types.held
class tee:
    taste = "bitter" # coffee, ftw ;)

@food_types.held
class lemon:
    taste = "sour"

print(food_types['bacon'].taste) # No manual add_class needed! :D
structure

Réponses similaires à “Utilisation des décorateurs”

Questions similaires à “Utilisation des décorateurs”

Plus de réponses similaires à “Utilisation des décorateurs” dans Python

Parcourir les réponses de code populaires par langue

Parcourir d'autres langages de code