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

PREVIOUS NEXT
Code Example
Python :: mongodb in python 
Python :: math module in python 
Python :: read csv python 
Python :: pandas groupby most frequent 
Python :: pil format multiline text 
Python :: anagrams string python 
Python :: how to find the longest string python 
Python :: Difference between two dates and times in python 
Python :: python lambda key sort 
Python :: python function with infinite parameters 
Python :: Local to ISO 8601: 
Python :: free download django app for windows 10 
Python :: calculate quantiles python 
Python :: adam optimizer keras learning rate degrade 
Python :: python min key 
Python :: pandas series example 
Python :: django authenticate with email 
Python :: number of elements in the array numpy 
Python :: python A string float numeral into integer 
Python :: python max 
Python :: python library for downsampling a photo 
Python :: python script that turns bluetooth on 
Python :: python extract all characters from string before a character 
Python :: Appending rows to a DataFrame 
Python :: drf serializer general validate method 
Python :: find index of element in array python 
Python :: data type array 
Python :: x y coordinates in python 
Python :: array with zeros python 
Python :: python glob.glob recursive 
ADD CONTENT
Topic
Content
Source link
Name
3+8 =