avatarYong Cui

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

9500

Abstract

</span> <span class="language-python">user1.greet(user0)</span> Batman: Hello, Superman!</pre></div><p id="6a6e">To use the class, in the above code, we created two users, namely <code>user0</code> and <code>user1</code>. As you can see, we could easily access the instance attributes using the dot notation. The defined <code>greet()</code> function was called by the instance object. To learn more about the declaration of Python custom classes, you can refer to my previous article on this topic.</p><div id="38f8" class="link-block"> <a href="https://readmedium.com/declare-your-first-python-class-understand-3-basic-components-15768c8d35b0"> <div> <div> <h2>Declare Your First Python Class — Understand 3 Basic Components</h2> <div><h3>Better organize your code using custom classes</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*-cp54P2ybx_GZwbI)"></div> </div> </div> </a> </div><h1 id="e0a8">Decorators for Custom Classes</h1><p id="bc30">I hope that you have a better understanding of the basics of Python decorators and custom classes through the above overviews. In this section, we’re going to learn three commonly used decorators in declaring custom classes.</p><h2 id="8df9">The Class Method Decorator</h2><p id="eff7">The first decorator is called <i>classmethod</i>. As indicated by its name, this decorator function decorates class methods. But what are class methods in Python? To understand what a class method is, let’s step back and take a quick look at the <code>greet()</code> function above.</p><p id="6b78">Notice that the <code>greet()</code> function’s first argument is <i>self</i>, which refers to the instance object that calls this method. Thus, we refer to this function as an instance method. Unlike the instance method, a <b>class method</b> is called by the class (in reality, it can be called by the instance too, but the instance is ignored). The first parameter of the class method is named as <i>cls</i>, as a convention to refer to the class. It has the following syntax.</p><div id="4cd2"><pre><span class="hljs-meta">@classmethod</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">funcname</span>(<span class="hljs-params">cls, arg1, arg2, ...</span>): <span class="hljs-keyword">pass</span></pre></div><p id="a469">Let’s see how we use the <i>classmethod</i> decorator in action. We’ll continue to use the <code>User</code> class that was declared in the previous section.</p><div id="8acb"><pre><span class="hljs-meta prompt_">>>></span> <span class="language-python"><span class="hljs-comment"># Update the class by declaring a class method</span></span> <span class="hljs-meta prompt_">>>></span> <span class="language-python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">User</span>:</span> <span class="hljs-meta prompt_">...</span> <span class="language-python"> <span class="hljs-comment"># init and greet() stay the same</span></span> <span class="hljs-meta prompt_">...</span> <span class="hljs-meta prompt_">...</span> <span class="language-python"><span class="hljs-meta"> @classmethod</span></span> <span class="hljs-meta prompt_">...</span> <span class="language-python"> <span class="hljs-keyword">def</span> <span class="hljs-title function_">user_from_dict</span>(<span class="hljs-params">cls, user_dict</span>):</span> <span class="hljs-meta prompt_">...</span> <span class="language-python"> username = user_dict[<span class="hljs-string">"username"</span>]</span> <span class="hljs-meta prompt_">...</span> <span class="language-python"> email = user_dict[<span class="hljs-string">"email"</span>]</span> <span class="hljs-meta prompt_">...</span> <span class="language-python"> <span class="hljs-keyword">return</span> cls(username, email)</span> <span class="hljs-meta prompt_">...</span></pre></div><p id="eb67">As shown in the above code, we declared a class method called <code>user_from_dict</code>. As discussed above, the first argument is <i>cls</i>. What this class method does is to create a <code>User</code> instance from a dictionary. More broadly speaking, we often use <b><i>a class method as a factory method that creates an instance object</i></b>, as an alternative to the default constructor method, as defined in the <code>init</code> function.</p><p id="4d1f">As you may know, it’s common that a website can allow you to log in using a social account. For simplicity, suppose that we obtain the user’s information from one social networking platform. We then want to create a user from the parsed dictionary object using the class method. Let’s see how it works below.</p><div id="e148"><pre><span class="hljs-meta prompt_">>>></span> <span class="language-python"><span class="hljs-comment"># Create a user from a dict that is created from JSON response</span></span> <span class="hljs-meta prompt_">>>></span> <span class="language-python">user_dict = {<span class="hljs-string">"username"</span>: <span class="hljs-string">"Spider-Man"</span>, <span class="hljs-string">"email"</span>: <span class="hljs-string">"[email protected]"</span>}</span> <span class="hljs-meta prompt_">>>></span> <span class="language-python">user2 = User.user_from_dict(user_dict)</span> <span class="hljs-meta prompt_">>>></span> <span class="hljs-meta prompt_">>>></span> <span class="language-python"><span class="hljs-comment"># Check the type</span></span> <span class="hljs-meta prompt_">>>></span> <span class="language-python"><span class="hljs-built_in">isinstance</span>(user2, User)</span> True <span class="hljs-meta prompt_">>>></span> <span class="hljs-meta prompt_">>>></span> <span class="language-python"><span class="hljs-comment"># Access attributes and call the instance method</span></span> <span class="hljs-meta prompt_">>>></span> <span class="language-python">user2.username</span> 'Spider-Man' <span class="hljs-meta prompt_">>>></span> <span class="language-python">user2.greet(user0)</span> Spider-Man: Hello, Superman!</pre></div><p id="e7a0">As shown above, we used the class method to create an instance object of the <code>User</code> class. Using the introspection function isinstance(), we verified that the new object is indeed a <code>User</code> instance. In addition, the new object <code>user2</code> has access to instance attributes and methods.</p><h2 id="da7c">The Static Method Decorator</h2><p id="99f5">The second decorator is called <i>staticmethod</i>. As indicated by its name, this decorator function decorates static methods. But what are static methods in Python?</p><p id="3b10">The static method has the following basic syntax. As you can see, unlike the class method, it doesn’t have <i>cls</i> as its first argument, and thus it doesn’t intend to directly work with the class. Unlike the instance method, it doesn’t have <i>self</i> as its first argument, and thus it doesn’t intend to directly work with any instance too. In other words, <b><i>a static method in Python performs some utility operations independent of the class or any specific instance.</i></b></p><div id="95f1"><pre><span class="hljs-meta">@staticmethod</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">funcname</span>(<span class="hljs-params">arg1, arg2, ...</span>): <span class="hljs-keyword">pass</span></pre></div><p id="3603">Let’s see how we can use the <i>staticmethod</i> decorator in the code below.</p><div id="b63c"><pre><span class="hljs-meta prompt_">>>></span> <span class="language-python"><span class="hljs-comment"># Update the class with a static method</span></span> <span class="hljs-meta prompt_">>>></span> <span class="language-python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">User</span>:</span> <span class="hljs-meta prompt_">...</span> <span class="language-python"> <span class="hljs-comment"># Other code stays the same</span></span> <span class="hljs-meta prompt_">...</span> <span class="hljs-meta prompt_">...</span> <span class="language-python"><span class="hljs-meta"> @staticmethod</span></span> <span class="hljs-meta prompt_">...</span> <span class="language-python"> <span class="hljs-keyword">def</span> <span class="hljs-title function_">username_valid</span>(<span class="hljs-params">username</span>):</span> <span class="hljs-meta prompt_">...</span> <span class="language-python"> <span class="hljs-keyword">return</span> <span class="hljs-built_in">len</span>(username) < <span class="hljs-number">10</span> <span class="hljs-keyword">and</span> username.endswith(<span class="hljs-string">"man"</span>)</span> <span class="hljs-meta prompt_">...</span></pre></div><p id="51f0">As shown, we declared a static method called <code>username_valid</code>, the operation of which is simply to check if a string is a valid username or not. This operation certainly doesn’t have to depend on the class or an instance object. Here are some examples showing how we can call this static method. One thing to note is that we can also use an instance object to call the static method, but the instance

Options

is actually just ignored by the function.</p><div id="ac6b"><pre>>>> # <span class="hljs-keyword">Try</span> <span class="hljs-keyword">using</span> the <span class="hljs-keyword">static</span> <span class="hljs-keyword">method</span> >>> <span class="hljs-title function_">User</span>.<span class="hljs-title function_">username_valid</span><span class="hljs-params">("Superman")</span> <span class="hljs-title function_">True</span> >>> <span class="hljs-title function_">User</span>.<span class="hljs-title function_">username_valid</span><span class="hljs-params">("Superboy")</span> <span class="hljs-title function_">False</span> >>> <span class="hljs-title function_">user0</span>.<span class="hljs-title function_">username_valid</span><span class="hljs-params">("Super-Superman")</span> <span class="hljs-title function_">False</span></pre></div><h2 id="ffbf">The Property Decorator</h2><p id="f3fb">The third decorator is called <i>property</i>. In many other object-oriented programming languages, they don’t really differentiate attributes and properties, both of which can refer to the data fields of a particular object.</p><p id="c310">In Python, for most cases, we use attributes to refer to these data fields. When we say properties in Python, we refer to <b><i>instance methods that are decorated by the property decorator</i></b>. At its core, a property is an instance method.</p><p id="2964">But why do we use the property decorator then? One major reason is that we can easily use dot notation to retrieve related data for the instance object instead of explicitly calling the specific function. If you’re interested in knowing more about the <i>property</i> decorator, you can refer to my previous article on this topic.</p><div id="5d90" class="link-block"> <a href="https://readmedium.com/why-bother-using-property-decorators-in-python-935c425f86ed"> <div> <div> <h2>Why Bother Using Property Decorators in Python?</h2> <div><h3>Have a deeper understanding of @property</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/0*zMnoWjUkgAxR4LcZ)"></div> </div> </div> </a> </div><p id="a244">Let’s see an example such that it’ll be easier for me to explain how we can use it. Suppose that some websites allow you to change the display name after the registration, which is initially set to something based on the username. We can design the display name managed as a property. Let’s implement this functionality using the <i>property</i> decorator. See the code below first.</p><div id="e5ed"><pre><span class="hljs-meta prompt_">>>></span> <span class="language-python"><span class="hljs-comment"># Update the class with the property method</span></span> <span class="hljs-meta prompt_">>>></span> <span class="language-python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">User</span>:</span> <span class="hljs-meta prompt_">...</span> <span class="language-python"> <span class="hljs-keyword">def</span> <span class="hljs-title function_">init</span>(<span class="hljs-params">self, username, email</span>):</span> <span class="hljs-meta prompt_">...</span> <span class="language-python"> self.username = username</span> <span class="hljs-meta prompt_">...</span> <span class="language-python"> self.email = email</span> <span class="hljs-meta prompt_">...</span> <span class="language-python"> self._display_name = <span class="hljs-string">f"@<span class="hljs-subst">{username}</span>"</span></span> <span class="hljs-meta prompt_">...</span> <span class="hljs-meta prompt_">...</span> <span class="language-python"><span class="hljs-meta"> @property</span></span> <span class="hljs-meta prompt_">...</span> <span class="language-python"> <span class="hljs-keyword">def</span> <span class="hljs-title function_">display_name</span>(<span class="hljs-params">self</span>):</span> <span class="hljs-meta prompt_">...</span> <span class="language-python"> <span class="hljs-built_in">print</span>(<span class="hljs-string">"display_name is called"</span>)</span> <span class="hljs-meta prompt_">...</span> <span class="language-python"> <span class="hljs-keyword">return</span> self._display_name</span> <span class="hljs-meta prompt_">...</span></pre></div><p id="4980">Specifically, we created a property by using the <i>property</i> decorator that is placed above an instance method. The instance method has the <i>self</i> as its first argument, such that it can have access to an instance’s attributes — still remember it? With the <i>property</i> decorator, we can use the dot notation to retrieve the <code>display_name</code> now, as shown below.</p><div id="80d9"><pre><span class="hljs-meta prompt_">>>></span> <span class="language-python"><span class="hljs-comment"># Declare a user and access its property</span></span> <span class="hljs-meta prompt_">>>></span> <span class="language-python">user0 = User(<span class="hljs-string">"Superman"</span>, <span class="hljs-string">"[email protected]"</span>)</span> <span class="hljs-meta prompt_">>>></span> <span class="language-python">user0.display_name</span> display_name is called '@Superman'</pre></div><p id="ab44">What will happen if we want to change the property? Unfortunately, you can’t do it, because a property isn’t really an attribute, at its core.</p><div id="6a67"><pre>>>> user0.display_name = <span class="hljs-comment">'@Super Duper Man'</span> Traceback (most recent <span class="hljs-keyword">call</span> last): File <span class="hljs-string">"<stdin>"</span>, line <span class="hljs-number">1</span>, <span class="hljs-keyword">in</span> <<span class="hljs-keyword">module</span>> <span class="hljs-symbol">AttributeError:</span> can<span class="hljs-comment">'t set attribute</span></pre></div><p id="72df">To fix this problem, we can take advantage of the <i>property</i> decorator’s setter method. An updated version of the code will look like below.</p><div id="705c"><pre><span class="hljs-meta prompt_">>>></span> <span class="language-python"><span class="hljs-comment"># Update the property's setter method</span></span> <span class="hljs-meta prompt_">>>></span> <span class="language-python"><span class="hljs-keyword">class</span> <span class="hljs-title class_">User</span>:</span> <span class="hljs-meta prompt_">...</span> <span class="language-python"> <span class="hljs-comment"># Other code stays the same</span></span> <span class="hljs-meta prompt_">...</span> <span class="hljs-meta prompt_">...</span> <span class="language-python"><span class="hljs-meta"> @display_name.setter</span></span> <span class="hljs-meta prompt_">...</span> <span class="language-python"> <span class="hljs-keyword">def</span> <span class="hljs-title function_">display_name</span>(<span class="hljs-params">self, new_name</span>):</span> <span class="hljs-meta prompt_">...</span> <span class="language-python"> <span class="hljs-built_in">print</span>(<span class="hljs-string">"Setter method is called"</span>)</span> <span class="hljs-meta prompt_">...</span> <span class="language-python"> self._display_name = new_name</span> <span class="hljs-meta prompt_">...</span></pre></div><p id="3bcc">As shown in the code, we’ll just use the property’s name (i.e., display_name) followed by setter to decorate the instance method. With that, this method will be used as the setter method for the property. See its usage now.</p><div id="7bef"><pre>>>> user0.display_name = <span class="hljs-string">'Super Duper Man'</span> Setter <span class="hljs-keyword">method</span> <span class="hljs-title function_">is</span> <span class="hljs-title function_">called</span> >>> <span class="hljs-title function_">user0</span>.<span class="hljs-title function_">display_name</span> <span class="hljs-title function_">display_name</span> <span class="hljs-title function_">is</span> <span class="hljs-title function_">called</span> '<span class="hljs-title function_">Super</span> <span class="hljs-title function_">Duper</span> <span class="hljs-title function_">Man</span>'</pre></div><p id="3a56">We can also implement a <i>deleter</i> method for the property, and if you want to learn more about the <i>decorator</i> property, please feel free to refer to the article that I shared above.</p><h1 id="c265">Conclusions</h1><p id="4cf3">In this article, we first reviewed the decorators and custom classes in general. We then went over three commonly used decorators in Python custom classes, including <i>classmethod</i>, <i>staticmethod</i>, and <i>property</i>. Here’s a quick re-cap for these decorators.</p><ul><li>The <i>classmethod</i> decorator is to create a class method. In Python, a class method is usually used as a factory function to create new instance objects.</li><li>The <i>staticmethod</i> decorator is to create a static method, which usually performs some utility operations independent of the class or any instance.</li><li>The <i>property</i> decorator is to create a property from an instance method, such that we can access some functions like regular attributes.</li></ul></article></body>

Level Up Your Python Skills

Three Decorators Commonly Used in Python Custom Classes

Make your code more stylish

Photo by vitoandwilly on Unsplash

Introduction

Overview of Decorators

Decorators are a unique feature in Python that is not too common among other programming languages. As implied by its name, the job of a decorator is to modify another function’s behavior without affecting the decorated function’s core functionality.

Using a metaphor, let’s say the to-be-decorated function is a plain donut. You can conceptualize decorators as different coatings for the donut. No matter what the coating is — sugar, chocolate, honeybee, or whatever, a donut is still a kind of fried ring-shaped dough food.

Let’s forget about donuts (already feel wanting some sweets?) and move on to an actual example of a simple Python decorator. Through the example, we can have some ideas about what the decoration means.

>>> # Define a decorator function
>>> def show_start_end(func):
...      def inner_func():
...          print(f"Before calling func {func.__name__}")
...          func()
...          print(f"After calling func {func.__name__}")
...      return inner_func
... 

As shown in the above code, we first declared a decorator function named show_start_end, which takes another function as its argument. Within the decorator function, we called the passed function. Importantly, we requested the console to print two strings before and after calling the passed function.

>>> # Declare a function that is decorated
>>> @show_start_end
... def say_hello():
...     print(f"Hello, World!")
... 
>>> # Call the function
>>> say_hello()
Before calling func say_hello
Hello, World!
After calling func say_hello

As shown above, to use the decorator function, we just used an @ sign preceding the function name (i.e., @show_start_end) and placed it above a regular definition of a function. As you can see, when we called the decorated function, the two strings before and after displaying the string from calling the say_hello() function were shown as expected.

To learn more about decorators, you can refer to my previous articles on this topic. Here are the links for your convenience.

Overview of Custom Classes

At its core, Python is an object-oriented general-purpose programming language. All of its data and functionalities are managed using various kinds of objects. To better manage and manipulate the data in our projects, it’s very common that we create custom classes.

Suppose that we’re working on an online forum project. One of the needed data structures is to manage user-related data. For this purpose, we can create a custom class called User, and a much-simplified version of this class is shown below. Undoubtedly, in reality, it’ll be much more complicated.

>>> # Create a custom class for user data management
>>> class User:
...     def __init__(self, username, email):
...         self.username = username
...         self.email = email
...
...     # Greet another user
...     def greet(self, other_user):
...         print(f"{self.username}: Hello, {other_user.username}!")
...

In the above code snippet, we created a custom class called User. In the class, we defined the __init__ method, which will be used as the constructor for the class. In addition, we declared another function called greet, which is an instance method that allows one user to greet another user.

>>> # Declare a user and check its attributes
>>> user0 = User("Superman", "[email protected]")
>>> user0.username
'Superman'
>>> user0.email
'[email protected]'
>>> 
>>> # Create another user and call the greet() function
>>> user1 = User("Batman", "[email protected]")
>>> user1.greet(user0)
Batman: Hello, Superman!

To use the class, in the above code, we created two users, namely user0 and user1. As you can see, we could easily access the instance attributes using the dot notation. The defined greet() function was called by the instance object. To learn more about the declaration of Python custom classes, you can refer to my previous article on this topic.

Decorators for Custom Classes

I hope that you have a better understanding of the basics of Python decorators and custom classes through the above overviews. In this section, we’re going to learn three commonly used decorators in declaring custom classes.

The Class Method Decorator

The first decorator is called classmethod. As indicated by its name, this decorator function decorates class methods. But what are class methods in Python? To understand what a class method is, let’s step back and take a quick look at the greet() function above.

Notice that the greet() function’s first argument is self, which refers to the instance object that calls this method. Thus, we refer to this function as an instance method. Unlike the instance method, a class method is called by the class (in reality, it can be called by the instance too, but the instance is ignored). The first parameter of the class method is named as cls, as a convention to refer to the class. It has the following syntax.

@classmethod
def funcname(cls, arg1, arg2, ...):
    pass

Let’s see how we use the classmethod decorator in action. We’ll continue to use the User class that was declared in the previous section.

>>> # Update the class by declaring a class method
>>> class User:
...     # __init__ and greet() stay the same
...
...     @classmethod
...     def user_from_dict(cls, user_dict):
...         username = user_dict["username"]
...         email = user_dict["email"]
...         return cls(username, email)
...

As shown in the above code, we declared a class method called user_from_dict. As discussed above, the first argument is cls. What this class method does is to create a User instance from a dictionary. More broadly speaking, we often use a class method as a factory method that creates an instance object, as an alternative to the default constructor method, as defined in the __init__ function.

As you may know, it’s common that a website can allow you to log in using a social account. For simplicity, suppose that we obtain the user’s information from one social networking platform. We then want to create a user from the parsed dictionary object using the class method. Let’s see how it works below.

>>> # Create a user from a dict that is created from JSON response
>>> user_dict = {"username": "Spider-Man", "email": "[email protected]"}
>>> user2 = User.user_from_dict(user_dict)
>>> 
>>> # Check the type
>>> isinstance(user2, User)
True
>>> 
>>> # Access attributes and call the instance method
>>> user2.username
'Spider-Man'
>>> user2.greet(user0)
Spider-Man: Hello, Superman!

As shown above, we used the class method to create an instance object of the User class. Using the introspection function isinstance(), we verified that the new object is indeed a User instance. In addition, the new object user2 has access to instance attributes and methods.

The Static Method Decorator

The second decorator is called staticmethod. As indicated by its name, this decorator function decorates static methods. But what are static methods in Python?

The static method has the following basic syntax. As you can see, unlike the class method, it doesn’t have cls as its first argument, and thus it doesn’t intend to directly work with the class. Unlike the instance method, it doesn’t have self as its first argument, and thus it doesn’t intend to directly work with any instance too. In other words, a static method in Python performs some utility operations independent of the class or any specific instance.

@staticmethod
def funcname(arg1, arg2, ...):
    pass

Let’s see how we can use the staticmethod decorator in the code below.

>>> # Update the class with a static method
>>> class User:
...     # Other code stays the same
...
...     @staticmethod
...     def username_valid(username):
...         return len(username) < 10 and username.endswith("man")
...

As shown, we declared a static method called username_valid, the operation of which is simply to check if a string is a valid username or not. This operation certainly doesn’t have to depend on the class or an instance object. Here are some examples showing how we can call this static method. One thing to note is that we can also use an instance object to call the static method, but the instance is actually just ignored by the function.

>>> # Try using the static method
>>> User.username_valid("Superman")
True
>>> User.username_valid("Superboy")
False
>>> user0.username_valid("Super-Superman")
False

The Property Decorator

The third decorator is called property. In many other object-oriented programming languages, they don’t really differentiate attributes and properties, both of which can refer to the data fields of a particular object.

In Python, for most cases, we use attributes to refer to these data fields. When we say properties in Python, we refer to instance methods that are decorated by the property decorator. At its core, a property is an instance method.

But why do we use the property decorator then? One major reason is that we can easily use dot notation to retrieve related data for the instance object instead of explicitly calling the specific function. If you’re interested in knowing more about the property decorator, you can refer to my previous article on this topic.

Let’s see an example such that it’ll be easier for me to explain how we can use it. Suppose that some websites allow you to change the display name after the registration, which is initially set to something based on the username. We can design the display name managed as a property. Let’s implement this functionality using the property decorator. See the code below first.

>>> # Update the class with the property method
>>> class User:
...     def __init__(self, username, email):
...         self.username = username
...         self.email = email
...         self._display_name = f"@{username}"
...
...     @property
...     def display_name(self):
...         print("display_name is called")
...         return self._display_name
...

Specifically, we created a property by using the property decorator that is placed above an instance method. The instance method has the self as its first argument, such that it can have access to an instance’s attributes — still remember it? With the property decorator, we can use the dot notation to retrieve the display_name now, as shown below.

>>> # Declare a user and access its property
>>> user0 = User("Superman", "[email protected]")
>>> user0.display_name
display_name is called
'@Superman'

What will happen if we want to change the property? Unfortunately, you can’t do it, because a property isn’t really an attribute, at its core.

>>> user0.display_name = '@Super Duper Man'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

To fix this problem, we can take advantage of the property decorator’s setter method. An updated version of the code will look like below.

>>> # Update the property's setter method
>>> class User:
...     # Other code stays the same
...
...     @display_name.setter
...     def display_name(self, new_name):
...         print("Setter method is called")
...         self._display_name = new_name
...

As shown in the code, we’ll just use the property’s name (i.e., display_name) followed by setter to decorate the instance method. With that, this method will be used as the setter method for the property. See its usage now.

>>> user0.display_name = 'Super Duper Man'
Setter method is called
>>> user0.display_name
display_name is called
'Super Duper Man'

We can also implement a deleter method for the property, and if you want to learn more about the decorator property, please feel free to refer to the article that I shared above.

Conclusions

In this article, we first reviewed the decorators and custom classes in general. We then went over three commonly used decorators in Python custom classes, including classmethod, staticmethod, and property. Here’s a quick re-cap for these decorators.

  • The classmethod decorator is to create a class method. In Python, a class method is usually used as a factory function to create new instance objects.
  • The staticmethod decorator is to create a static method, which usually performs some utility operations independent of the class or any instance.
  • The property decorator is to create a property from an instance method, such that we can access some functions like regular attributes.
Technology
Artificial Intelligence
Data Science
Programming
Python
Recommended from ReadMedium