Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

decorator python

def our_decorator(func):
    def function_wrapper(x):
        print("Before calling " + func.__name__)
        func(x)
        print("After calling " + func.__name__)
    return function_wrapper

@our_decorator
def foo(x):
    print("Hi, foo has been called with " + str(x))

foo("Hi")
Comment

python decorator

def uppercase_decorator(func):
    def function_wrapper(x):
        print("Before calling " + func.__name__)
        # function that is decorated making name parameter always uppercase
        func(x.upper())
        print("After calling " + func.__name__)
    return function_wrapper

@uppercase_decorator
def user(name):
    print(f"Hi, {name}")

user("Sam")

# output
# Before calling user
# Hi, SAM
# After calling user
Comment

python decorator

from functools import wraps
def debug(func):
    @wraps(func)
    def out(*args, **kwargs):
        print('hello world')
        return func(*args, **kwargs)
    return out

@debug
def add(x, y):
    return x + y
Comment

python decorator

# Decorator with arguments
import functools

# First function takes the wanted number of repetition
def repeat(num_times):
    # Second function takes the function
    def decorator_repeat(func):
        # Third function, the wrapper executes the function the number of times wanted        
        # functools decorator to print the true name of the function passed instead of "wrapper"
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            for _ in range(num_times):
                result= func(*args, **kwargs)
            return result
        return wrapper
    return decorator_repeat

# Our function using the decorator
@repeat(num_times= 3)
def greet(name):
    print(f"Hello {name}")

greet("thomas")
Comment

Decorators in python

# decorator function to convert to lowercase
def lowercase_decorator(function):
   def wrapper():
       func = function()
       string_lowercase = func.lower()
       return string_lowercase
   return wrapper
# decorator function to split words
def splitter_decorator(function):
   def wrapper():
       func = function()
       string_split = func.split()
       return string_split
   return wrapper
@splitter_decorator # this is executed next
@lowercase_decorator # this is executed first
def hello():
   return 'Hello World'
hello()   # output => [ 'hello' , 'world' ]
Comment

decorators in python

# this functon converts any string into uppercase
def deco(function):
    def wrap(s):
        return s.upper()
        function(s)
    return wrap

@deco
def display(s):
    return s 
print(display("not bad"))
Comment

decorators in python

def deco(function):
    def wrap(num):
        if num % 2 == 0:
            print(num,"is even ")
        else:
            print(num,"is odd")
        function(num)
    return wrap
    
@deco
def display(num):
    return num
display(9)   # pass any number to check whether number is even or odd
Comment

python decorator python

# class decorator 
import random

# changes the properties of a function to a class instance
class Eliphant:
    def __init__(self,funct):
        self._funct = funct
        #all return values are storredin momory
        self._memory = []

    def __call__(self):
        returnvalue = self._funct()
        self._memory.append(returnvalue)
        return returnvalue

    def memory(self):
        return self._memory


@Eliphant

def random_odd():
    return random.choice([1,3,5,7,9])
print(random_odd())
print(random_odd.memory())
print(random_odd())
print(random_odd.memory())
Comment

Decorators in python

# decorator function to convert to lowercase
def lowercase_decorator(function):
   def wrapper():
       func = function()
       string_lowercase = func.lower()
       return string_lowercase
   return wrapper
# decorator function to split words
def splitter_decorator(function):
   def wrapper():
       func = function()
       string_split = func.split()
       return string_split
   return wrapper
@splitter_decorator # this is executed next
@lowercase_decorator # this is executed first
def hello():
   return 'Hello World'
hello()   # output => [ 'hello' , 'world' ]
Comment

Decorators in Python

def first(msg):
    print(msg)


first("Hello")

second = first
second("Hello")
Comment

python decorator

def deco(func):
    def wrap(lst):
        x = [1 if i % 2 == 0 else 0 for i in lst]
        return x
        func(lst)
    return wrap

@deco  
Comment

PREVIOUS NEXT
Code Example
Python :: how to take multiple input in list in python 
Python :: runtime.txt heroku python 
Python :: force garbage collection in python 
Python :: starting vscode on colab 
Python :: python make directory tree from path 
Python :: python tkinter define window size 
Python :: django creating calculated fields in model 
Python :: find columns with missing values pandas 
Python :: add 2 set python 
Python :: python run shell command 
Python :: how to detect language python 
Python :: get string until character python 
Python :: barplot syntax in python 
Python :: python bold text in terminal 
Python :: how to write to the end of a file in python 
Python :: convert data type object to string python 
Python :: show integer seabron heatmap values 
Python :: how to say something python 
Python :: pandas number of columns 
Python :: keras.layers.MaxPool2D 
Python :: datetime.datetime.fromtimestamp() 
Python :: django ckeditor not working 
Python :: create close python program in puthon 
Python :: if dict.values <= int 
Python :: how to get pygame key 
Python :: python timestamp to datetime 
Python :: python convert exponential to int 
Python :: pandas length of array in column 
Python :: python var_dump 
Python :: deleting dataframe row in pandas based on column value 
ADD CONTENT
Topic
Content
Source link
Name
8+4 =