{"id":1017,"date":"2020-11-10T03:36:11","date_gmt":"2020-11-10T03:36:11","guid":{"rendered":"https:\/\/www.pythontutorial.net\/?page_id=1017"},"modified":"2025-03-27T13:56:03","modified_gmt":"2025-03-27T13:56:03","slug":"python-class-decorators","status":"publish","type":"page","link":"https:\/\/www.pythontutorial.net\/advanced-python\/python-class-decorators\/","title":{"rendered":"Python Class Decorators"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn about Python class decorators. After the tutorial, you&#8217;ll know how to define classes as decorators.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='introduction-to-the-python-class-decorators'>Introduction to the Python class decorators <a href=\"#introduction-to-the-python-class-decorators\" class=\"anchor\" id=\"introduction-to-the-python-class-decorators\" title=\"Anchor for Introduction to the Python class decorators\">#<\/a><\/h2>\n\n\n\n<p>So far you have learned how to use <a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-functions\/\">functions<\/a> to define <a href=\"https:\/\/www.pythontutorial.net\/advanced-python\/python-decorators\/\">decorators<\/a>. <\/p>\n\n\n\n<p>For example, the following <code>star<\/code> function prints out a number of <code>*<\/code> characters before and after calling the decorated function:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">star<\/span><span class=\"hljs-params\">(n)<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">decorate<\/span><span class=\"hljs-params\">(fn)<\/span>:<\/span>\n        <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">wrapper<\/span><span class=\"hljs-params\">(*args, **kwargs)<\/span>:<\/span>\n            print(n*<span class=\"hljs-string\">'*'<\/span>)\n            result = fn(*args, **kwargs)\n            print(result)\n            print(n*<span class=\"hljs-string\">'*'<\/span>)\n            <span class=\"hljs-keyword\">return<\/span> result\n        <span class=\"hljs-keyword\">return<\/span> wrapper\n    <span class=\"hljs-keyword\">return<\/span> decorate<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The <code>star<\/code> is a <a href=\"https:\/\/www.pythontutorial.net\/advanced-python\/python-decorator-arguments\/\">decorator factory<\/a> that returns a decorator. It accepts an argument that specifies the number of <code>*<\/code> characters to display.<\/p>\n\n\n\n<p>The following illustrates how to use the <code>star<\/code> decorator factory:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">star<\/span><span class=\"hljs-params\">(n)<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">decorate<\/span><span class=\"hljs-params\">(fn)<\/span>:<\/span>\n        <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">wrapper<\/span><span class=\"hljs-params\">(*args, **kwargs)<\/span>:<\/span>\n            print(n*<span class=\"hljs-string\">'*'<\/span>)\n            result = fn(*args, **kwargs)\n            print(result)\n            print(n*<span class=\"hljs-string\">'*'<\/span>)\n            <span class=\"hljs-keyword\">return<\/span> result\n        <span class=\"hljs-keyword\">return<\/span> wrapper\n    <span class=\"hljs-keyword\">return<\/span> decorate\n\n<span class=\"hljs-meta\">@star(5)<\/span>\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">add<\/span><span class=\"hljs-params\">(a, b)<\/span>:<\/span>\n    <span class=\"hljs-keyword\">return<\/span> a + b\n\n\nadd(<span class=\"hljs-number\">10<\/span>, <span class=\"hljs-number\">20<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pythontutorial.net\/playground\/?q=ZGVmIHN0YXIobik6CiAgICBkZWYgZGVjb3JhdGUoZm4pOgogICAgICAgIGRlZiB3cmFwcGVyKCphcmdzLCAqKmt3YXJncyk6CiAgICAgICAgICAgIHByaW50KG4qJyonKQogICAgICAgICAgICByZXN1bHQgPSBmbigqYXJncywgKiprd2FyZ3MpCiAgICAgICAgICAgIHByaW50KHJlc3VsdCkKICAgICAgICAgICAgcHJpbnQobionKicpCiAgICAgICAgICAgIHJldHVybiByZXN1bHQKICAgICAgICByZXR1cm4gd3JhcHBlcgogICAgcmV0dXJuIGRlY29yYXRlCgpAc3Rhcig1KQpkZWYgYWRkKGEsIGIpOgogICAgcmV0dXJuIGEgKyBiCgoKYWRkKDEwLCAyMCk%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\"><span><code class=\"hljs\">*****\n30\n*****<\/code><\/span><\/pre>\n\n\n<p>The <code>star()<\/code> decorator factory takes an argument and returns a callable. The callable takes an argument (<code>fn<\/code>) which is a function that will be decorated. Also, the callable can access the argument (<code>n<\/code>) passed to the decorator factory.<\/p>\n\n\n\n<p>A class instance can be a callable when it implements the <code><a href=\"https:\/\/www.pythontutorial.net\/python-built-in-functions\/python-callable\/\">__call__<\/a><\/code> method. Therefore, you can make the <code>__call__<\/code> method as a decorator.<\/p>\n\n\n\n<p>The following example rewrites the <code>star<\/code> decorator factory using a class instead:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Star<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__init__<\/span><span class=\"hljs-params\">(self, n)<\/span>:<\/span>\n        self.n = n\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__call__<\/span><span class=\"hljs-params\">(self, fn)<\/span>:<\/span>\n        <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">wrapper<\/span><span class=\"hljs-params\">(*args, **kwargs)<\/span>:<\/span>\n            print(self.n*<span class=\"hljs-string\">'*'<\/span>)\n            result = fn(*args, **kwargs)\n            print(result)\n            print(self.n*<span class=\"hljs-string\">'*'<\/span>)\n            <span class=\"hljs-keyword\">return<\/span> result\n        <span class=\"hljs-keyword\">return<\/span> wrapper<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>And you can use the <code>Star<\/code> class as a decorator like this:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-meta\">@Star(5)<\/span>\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">add<\/span><span class=\"hljs-params\">(a, b)<\/span>:<\/span>\n    <span class=\"hljs-keyword\">return<\/span> a + b<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The <code>@Star(5)<\/code> returns an instance of the <code>Star<\/code> class. That instance is a callable, so you can do something like:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">add = Star(<span class=\"hljs-number\">5<\/span>)(add)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>So you can use callable classes to decorate functions.<\/p>\n\n\n\n<p>Put it all together:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">from<\/span> functools <span class=\"hljs-keyword\">import<\/span> wraps\n\n\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">Star<\/span>:<\/span>\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__init__<\/span><span class=\"hljs-params\">(self, n)<\/span>:<\/span>\n        self.n = n\n\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">__call__<\/span><span class=\"hljs-params\">(self, fn)<\/span>:<\/span>\n<span class=\"hljs-meta\">        @wraps(fn)<\/span>\n        <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">wrapper<\/span><span class=\"hljs-params\">(*args, **kwargs)<\/span>:<\/span>\n            print(self.n*<span class=\"hljs-string\">'*'<\/span>)\n            result = fn(*args, **kwargs)\n            print(result)\n            print(self.n*<span class=\"hljs-string\">'*'<\/span>)\n            <span class=\"hljs-keyword\">return<\/span> result\n        <span class=\"hljs-keyword\">return<\/span> wrapper\n\n\n<span class=\"hljs-meta\">@Star(5)<\/span>\n<span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">add<\/span><span class=\"hljs-params\">(a, b)<\/span>:<\/span>\n    <span class=\"hljs-keyword\">return<\/span> a + b\n\n\nadd(<span class=\"hljs-number\">10<\/span>, <span class=\"hljs-number\">20<\/span>)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p><a href=\"https:\/\/www.pythontutorial.net\/playground\/?q=ZnJvbSBmdW5jdG9vbHMgaW1wb3J0IHdyYXBzCgoKY2xhc3MgU3RhcjoKICAgIGRlZiBfX2luaXRfXyhzZWxmLCBuKToKICAgICAgICBzZWxmLm4gPSBuCgogICAgZGVmIF9fY2FsbF9fKHNlbGYsIGZuKToKICAgICAgICBAd3JhcHMoZm4pCiAgICAgICAgZGVmIHdyYXBwZXIoKmFyZ3MsICoqa3dhcmdzKToKICAgICAgICAgICAgcHJpbnQoc2VsZi5uKicqJykKICAgICAgICAgICAgcmVzdWx0ID0gZm4oKmFyZ3MsICoqa3dhcmdzKQogICAgICAgICAgICBwcmludChyZXN1bHQpCiAgICAgICAgICAgIHByaW50KHNlbGYubionKicpCiAgICAgICAgICAgIHJldHVybiByZXN1bHQKICAgICAgICByZXR1cm4gd3JhcHBlcgoKCkBTdGFyKDUpCmRlZiBhZGQoYSwgYik6CiAgICByZXR1cm4gYSArIGIKCgphZGQoMTAsIDIwKQ%3D%3D\" target=\"_blank\" rel=\"noreferrer noopener\">Try it<\/a><\/p>\n\n\n\n<p>Output:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"plaintext\" data-shcb-language-slug=\"plaintext\"><span><code class=\"hljs language-plaintext\">*****\n30\n*****<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">plaintext<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">plaintext<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\" id='summary'>Summary <a href=\"#summary\" class=\"anchor\" id=\"summary\" title=\"Anchor for Summary\">#<\/a><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use callable classes as decorators by implementing the <code><a href=\"https:\/\/www.pythontutorial.net\/python-built-in-functions\/python-callable\/\">__call__<\/a><\/code> method.<\/li>\n\n\n\n<li>Pass the decorator arguments to the <code><a href=\"https:\/\/www.pythontutorial.net\/python-oop\/python-__init__\/\">__init__<\/a><\/code> method.<\/li>\n<\/ul>\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"1017\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/advanced-python\/python-class-decorators\/\"\n\t\t\t\tdata-post-title=\"Python Class Decorators\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"1017\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/advanced-python\/python-class-decorators\/\"\n\t\t\t\tdata-post-title=\"Python Class Decorators\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\t\t\t<input type=\"button\" name=\"wth-submit\" class=\"wth-btn wth-btn-submit\" id=\"wth-submit\" \/>\n\t\t\t<input type=\"button\" class=\"wth-btn wth-btn-cancel\" value=\"Cancel\" \/>\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you&#8217;ll learn about Python class decorators. After the tutorial, you&#8217;ll know how to define classes as decorators.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":757,"menu_order":11,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-1017","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/1017","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/comments?post=1017"}],"version-history":[{"count":3,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/1017\/revisions"}],"predecessor-version":[{"id":7116,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/1017\/revisions\/7116"}],"up":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/757"}],"wp:attachment":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/media?parent=1017"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}