Introduction to Decorators
Part of the Object Oriented Programming section of Coddy's Python journey — lesson 9 of 64.
Decorators are a way to modify or enhance functions and classes without changing their original code. They use the @ symbol.
Here is an example of a simple decorator:
def my_decorator(func):
def wrapper():
print("Before function runs")
func()
print("After function runs")
return wrapperApply the decorator using @:
@my_decorator
def say_hello():
print("Hello!")Call the decorated function:
say_hello()Output:
Before function runs
Hello!
After function runsThe @my_decorator is equivalent to writing:
def say_hello():
print("Hello!")
say_hello = my_decorator(say_hello)But the @ syntax is much cleaner and easier to read.
Key Point: Decorators wrap around functions to add extra functionality without modifying the original function code
Cheat sheet
Decorators modify or enhance functions without changing their original code using the @ symbol.
Basic decorator structure:
def my_decorator(func):
def wrapper():
print("Before function runs")
func()
print("After function runs")
return wrapperApply decorator using @:
@my_decorator
def say_hello():
print("Hello!")The @my_decorator syntax is equivalent to:
say_hello = my_decorator(say_hello)Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe self ParameterMethodsAttributesConstructor Method (__init__)Recap - Simple Calculator4Inheritance
Basic InheritanceThe super() FunctionMethod OverridingMultiple InheritanceMethod Resolution OrderRecap - Employee Hierarchy7Special Methods
Magic Methods IntroductionOperator OverloadingContainer Magic MethodsRecap - Custom List10Design Patterns Part 1
Intro to design patternSingleton PatternFactory PatternObserver PatternStrategy Pattern2Decorators
Introduction to DecoratorsProperty DecoratorStatic Method DecoratorClass Method Decorator5Polymorphism
Method Overriding RevisitedDuck TypingAbstract Classes and MethodsInterface DesignRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceMixinsStatic and Class MethodsClass DecoratorsContext Managers3Class Properties
Instance vs Class VariablesProperty DecoratorsPrivate AttributesRecap - Bank Account Manager6Encapsulation
Public, Protected, Private MemAccess ModifiersInformation HidingProperty Decorators AdvancedRecap - Student Records System12Project: Library Management
Project OverviewBook and User Classes