Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

# decorator

# 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. 
Comment

using decorators

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
Comment

basic decorator example

def log_result(func):
  def inner():
    res = func()
    print(res)
    return res
Comment

PREVIOUS NEXT
Code Example
Python :: how to repeat if statement in python 
Python :: check if the user is logged in django decorator 
Python :: Groups the DataFrame using the specified columns 
Python :: month name in python 
Python :: circle circumference python 
Python :: can only concatenate str (not "int") to str 
Python :: python json random number generator 
Python :: python division 
Python :: get dictionary values python 
Python :: python red table from pdf 
Python :: Video to text convertor in python 
Python :: convert pandas dataframe to dict with a column as key 
Python :: infinity python 
Python :: get definition of word python 
Python :: extract text from pdf python 
Python :: how to make python open an application on mac 
Python :: fullscreen cmd with python 
Python :: UnicodeDecodeError: ‘utf8’ codec can’t decode byte 
Python :: tkinter pack grid and place 
Python :: semicolon in python 
Python :: pandas loc condition 
Python :: undefined in python 
Python :: install django in windows 
Python :: remove multiple strings from list python 
Python :: python how to automatically restart flask sever 
Python :: how to calculate fibonacci numbers in python 
Python :: create a virtualenv python3 
Python :: keras conv2d batchnorm 
Python :: check if queryset is empty django template 
Python :: baeutifulsoup find element with text 
ADD CONTENT
Topic
Content
Source link
Name
9+4 =