Python DecoratorDecorators are one of the most helpful and powerful tools of Python. These are used to modify the behavior of the function. Decorators provide the flexibility to wrap another function to expand the working of wrapped function, without permanently modifying it. In Decorators, functions are passed as an argument into another function and then called inside the wrapper function. It is also called meta programming where a part of the program attempts to change another part of program at compile time. Before understanding the Decorator, we need to know some important concepts of Python. What are the functions in Python?Python has the most interesting feature that everything is treated as an object even classes or any variable we define in Python is also assumed as an object. Functions are first-class objects in the Python because they can reference to, passed to a variable and returned from other functions as well. The example is given below: Output: Hii Hii In the above program, when we run the code it give the same output for both functions. The func2 referred to function func1 and act as function. We need to understand the following concept of the function:
Inner FunctionPython provides the facility to define the function inside another function. These types of functions are called inner functions. Consider the following example: Output: We are in first function This is first child function This is second child function In the above program, it doesn't matter how the child functions are declared. The execution of the child function makes effect on the output. These child functions are locally bounded with the func() so they cannot be called separately. A function that accepts other function as an argument is also called higher order function. Consider the following example: Output: 9 21 In the above program, we have passed the sub() function and add() function as argument in operator() function. A function can return another function. Consider the below example: Output: Hello In the above program, the hi() function is nested inside the hello() function. It will return each time we call hi(). Decorating functions with parametersLet's have an example to understand the parameterized decorator function: Output: 2.0 Syntactic DecoratorIn the above program, we have decorated out_div() that is little bit bulky. Instead of using above method, Python allows to use decorator in easy way with @symbol. Sometimes it is called "pie" syntax. Output: 2.0 Reusing DecoratorWe can reuse the decorator as well by recalling that decorator function. Let's make the decorator to its own module that can be used in many other functions. Creating a file called mod_decorator.py with the following code: We can import mod_decorator.py in other file. Output: Hello There Hello There Python Decorator with ArgumentWe want to pass some arguments in function. Let's do it in following code: Output: TypeError: display() missing 1 required positional argument: 'name' As we can see that, the function didn't accept the argument. Running this code raises an error. We can fix this error by using *args and **kwargs in the inner wrapper function. Modifying the decorator.py as follows: Now wrapper_function() can accept any number of argument and pass them on the function. Output: Hello John Hello John Returning Values from Decorated FunctionsWe can control the return type of the decorated function. The example is given below: Output: We are created greeting We are created greeting Fancy DecoratorsLet's understand the fancy decorators by the following topic: Class DecoratorsPython provides two ways to decorate a class. Firstly, we can decorate the method inside a class; there are built-in decorators like @classmethod, @staticmethod and @property in Python. The @classmethod and @staticmethod define methods inside class that is not connected to any other instance of a class. The @property is generally used to modify the getters and setters of a class attributes. Let’s understand it by the following example: Example: 1- @property decorator - By using it, we can use the class function as an attribute. Consider the following code: Output: Name: John Grade: B John got grade B Example:2 - @staticmethod decorator- The @staticmethod is used to define a static method in the class. It is called by using the class name as well as instance of the class. Consider the following code: Output: Hello Peter Hello Peter Singleton ClassA singleton class only has one instance. There are many singletons in Python including True, None, etc. Nesting DecoratorsWe can use multiple decorators by using them on top of each other. Let's consider the following example: In the above code, we have used the nested decorator by stacking them onto one another. Decorator with ArgumentsIt is always useful to pass arguments in a decorator. The decorator can be executed several times according to the given value of the argument. Let us consider the following example: Output: JavatPoint JavatPoint JavatPoint JavatPoint JavatPoint In the above example, @repeat refers to a function object that can be called in another function. The @repeat(num = 5) will return a function which acts as a decorator. The above code may look complex but it is the most commonly used decorator pattern where we have used one additional def that handles the arguments to the decorator. Note: Decorator with argument is not frequently used in programming, but it provides flexibility. We can use it with or without argument.Stateful DecoratorsStateful decorators are used to keep track of the decorator state. Let us consider the example where we are creating a decorator that counts how many times the function has been called. Output: Call 1 of 'say_hello' Say Hello Call 2 of 'say_hello' Say Hello In the above program, the state represented the number of calls of the function stored in .num_calls on the wrapper function. When we call say_hello() it will display the number of the call of the function. Classes as DecoratorsThe classes are the best way to maintain state. In this section, we will learn how to use a class as a decorator. Here we will create a class that contains __init__() and take func as an argument. The class needs to be callable so that it can stand in for the decorated function. To making a class callable, we implement the special __call__() method. Output: Call 1 of 'say_hello' Say Hello Call 2 of 'say_hello' Say Hello Call 3 of 'say_hello' Say Hello The __init__() method stores a reference to the function and can do any other required initialization. Next TopicPython Generators
|
Python tutorial provides basic and advanced concepts of Python.
Vue.js is an open-source progressive JavaScript framework
HTML refers to Hypertext Markup Language. HTML is the gateway ...
Java is an object-oriented, class-based computer-programming language.
PHP is an open-source,interpreted scripting language.
Spring is a lightweight framework.Spring framework makes ...
JavaScript is an scripting language which is lightweight and cross-platform.
CSS refers to Cascading Style Sheets...
jQuery is a small and lightweight JavaScript library. jQuery ...
SQL is used to perform operations on the records stored in the database.
C programming is considered as the base for other programming languages.
JavaScript is an scripting language which is lightweight and cross-platform.
Vue.js is an open-source progressive JavaScript framework
ReactJS is a declarative, efficient, and flexible JavaScript library.
jQuery is a small and lightweight JavaScript library. jQuery ...
Node.js is a cross-platform environment and library for running JavaScript app...
TypeScript is a strongly typed superset of JavaScript which compiles to plain JavaScript.
Angular JS is an open source JavaScript framework by Google to build web app...
JSON is lightweight data-interchange format.
AJAX is an acronym for Asynchronous JavaScript and XML.
ES6 or ECMAScript 6 is a scripting language specification ...
Angular 7 is completely based on components.
jQuery UI is a set of user interface interactions built on jQuery...
Python tutorial provides basic and advanced concepts of Python.
Java is an object-oriented, class-based computer-programming language.
Node.js is a cross-platform environment and library for running JavaScript app...
PHP is an open-source,interpreted scripting language.
Go is a programming language which is developed by Google...
C programming is considered as the base for other programming languages.
C++ is an object-oriented programming language. It is an extension to C programming.
C# is a programming language of .Net Framework.
Ruby is an open-source and fully object-oriented programming language.
JSP technology is used to create web application just like Servlet technology.
The JSTL represents a set of tags to simplify the JSP development.
ASP.NET is a web framework designed and developed by Microsoft.
Perl is a cross-platform environment and library for running JavaScript...
Scala is an object-oriented and functional programming language.
VBA stands for Visual Basic for Applications.
Spring is a lightweight framework.Spring framework makes ...
Spring Boot is a Spring module that provides the RAD feature...
Django is a Web Application Framework which is used to develop web applications.
Servlet technology is robust and scalable because of java language.
The Struts 2 framework is used to develop MVC based web applications.
Hibernate is an open source, lightweight, ORM tool.
Solr is a scalable, ready-to-deploy enterprise search engine.
SQL is used to perform operations on the records stored in the database.
MySQL is a relational database management system based...
Oracle is a relational database management system.
SQL Server is software developed by Microsoft.
PostgreSQL is an ORDBMS.
DB2 is a database server developed by IBM.
Redis is a No SQL database which works on the concept of key-value pair.
SQLite is embedded relational database management system.
MongoDB is a No SQL database. It is an document-oriented database...
Memcached is a free, distributed memory object caching system.
Hibernate is an open source, lightweight, ORM tool.
PL/SQL is a block structured language that can have multiple blocks in it.
DBMS Tutorial is software that is used to manage the database.
Spark is a unified analytics engine for large-scale data processing...
IntelliJ IDEA is an IDE for Java Developers which is developed by...
Git is a modern and widely used distributed version control system in the world.
GitHub is an immense platform for code hosting.
SVN is an open-source centralized version control system.
Maven is a powerful project management tool that is based on POM.
Jsoup is a java html parser.
UML is a general-purpose, graphical modeling language.
RESTful Web Services are REST Architecture based Web Services.
Postman is one testing tools which is used for API testing.
JMeter is to analyze the performance of web application.
Jenkins builds and tests our software projects.
SEO stands for Search Engine Optimization.
MATLAB is a software package for mathematical computation, visualization...
Unity is an engine for creating games on multiple platforms.
Hadoop is an open source framework.
Pig is a high-level data flow platform for executing Map Reduce programs of Hadoop.
Spark is a unified analytics engine for large-scale data processing...
Spring Cloud is a framework for building robust cloud applications.
Spring Boot is a Spring module that provides the RAD feature...
AI is one of the fascinating and universal fields of Computer.
Cloud computing is a virtualization-based technology.
AWS stands for Amazon Web Services which uses distributed IT...
Microsoft Azure is a cloud computing platform...
IoT stands for Internet of Things...
Spring Cloud is a framework for building robust cloud applications.
Email:jjw.quan@gmail.com