Python Zero to Heros

Online Absolute Beginner Python Tutorials 

Every Sunday 2pm (UK time/ BST)

Get this slide deck: https://slides.com/cheukting_ho/python-decorators

Recap

Python objects - int, float, str, list, dict, bool

Control flows - if-else, for loop, while loop

Functions, modeuls and classes

pytest

 

Any Questions?

Decorators

One way to think of decorators, it's like a function factory

functions are objects in Python

def greeting_factory():
  def greeting(name):
    print(f"Hello, {name}")
  return greeting

my_greeting = greeting_factory()
print(my_greeting)
my_greeting("Cheuk")

What is my_greeting?

What's inside my_greeting? (use dir)

Decorators

What if I have a greeting but I want to spice it up with some tractor jokes

def greeting(name):
  print(f"Hello, {name}")

def adding_jokes(greeting):
  def better_greeting(name):
    greeting(name)
    print("How did the farmer find his missing cow? He tractor down")
  return better_greeting

greeting("Cheuk")
print("Now make it better")
greeting = adding_jokes(greeting)
greeting("Cheuk")

What's going on here?

Decorators

To use a decorator, adding it with `@` before the function

def adding_jokes(greeting):
  def better_greeting(name):
    greeting(name)
    print("How did the farmer find his missing cow? He tractor down")
  return better_greeting

@adding_jokes
def greeting(name):
  print(f"Hello, {name}")

greeting("Cheuk")

What are we missing?

Decorators

decorator to help writing decorators

from functools import wraps

def adding_jokes(greeting):
  @wraps(greeting)
  def better_greeting(*args, **kwargs):
    greeting(*args, **kwargs)
    print("How did the farmer find his missing cow? He tractor down")
  return better_greeting

@adding_jokes
def greeting(name):
  print(f"Hello, {name}")

greeting("Cheuk")

When to use decorators?

Decorators

decorators can be useful for:
Authorization - if the function can be run

Testing - e.g. modify the function with parameters

OOP - property decorators - getters and setters

class person:
    def __init__(self):
        self.__name=''
    @property
    def name(self):
        return self.__name
    @name.setter
    def name(self, value):
        self.__name=value
    @name.deleter
    def name(self, value):
        print('Deleting..')
        del self.__name

Let's try writing some properties

 

Simple E-comerce similator ( e-shop.py)

 

https://github.com/Cheukting/python02hero/tree/master/2020-05-24-python-decorators

Homework 📝

 

There is no homework :-)

Next week:
String methods and Regex

Sunday 2pm (UK time/ BST)

There are also Mid Meet Py every Wednesday 1pm

Testing month in June

Python Decorators

By Cheuk Ting Ho

Python Decorators

  • 1,526