Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python staticmethod()

#1
Python staticmethod()

<div><p class="has-pale-cyan-blue-background-color has-background">Static methods are special cases of class methods. They’re bound to a class rather than an instance, so they’re independent on any instance’s state. Python’s built-in function <code><code>staticmethod</code>()</code> prefixes a method definition as an annotation <code>@staticmethod</code>. This annotation transforms a normal instance method into a static method. The difference between static (class) methods and instance methods is that they don’t require an instance to be callable. </p>
<p>In this tutorial, I’ll show you one of Python’s little-known secrets that separate the intermediates from the experts: <strong><em>static methods</em></strong>. A static method is a special case of a <strong>c<em>lass </em></strong><em><strong>method</strong></em>. You may know the difference between an <strong><em>instance method</em></strong> and a class method conceptually. (If you don’t, this tutorial is for you.) But do you also know how to create a static method in Python? </p>
<p>If not, read on, because this tutorial will show you!</p>
<h2>Syntax Class Method</h2>
<pre class="wp-block-preformatted"><strong>Syntax</strong>: <code>staticmethod(function)</code> # &lt;--- This is considered unpythonic
<code>@staticmethod</code> # &lt;--- As a prefix before the used method</pre>
<p>You can declare a static method is the following decorator syntax—this is the most Pythonic way:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class C: @staticmethod def f(arg1, arg2, ...): None C.f(arg1, arg2, ...)</pre>
<h2>How to Call a Static Method?</h2>
<p>There are two ways of calling a static method: </p>
<ul>
<li>You can call it on a class such as <code>C.f(arg1, arg2, ...)</code>, or</li>
<li>You can call it on an instance such as <code>C().f(arg1, arg2, ...)</code>. </li>
</ul>
<p>In contrast to a <a href="https://blog.finxter.com/python-classmethod/" title="Python classmethod()" target="_blank" rel="noreferrer noopener">class method</a>, Python doesn’t implicitly pass a reference to the class itself as a first argument.</p>
<h2>Static Method Application — Factory Pattern</h2>
<p>You can use the static method to allow people to create different variants of a <code>Coffee</code> class:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class Coffee: def __init__(self, milk, beans): self.milk = milk # percentage self.coffee = 100-milk # percentage self.beans = beans def __repr__(self): return f'Milk={self.milk}% Coffee={self.coffee}% Beans={self.beans}' @staticmethod def cappuccino(): return Coffee(80, 'Arrabica') @staticmethod def espresso_macchiato(): return Coffee(30, 'Robusta') @staticmethod def latte(): return Coffee(95, 'Arrabica') print(Coffee.cappuccino())
print(Coffee.espresso_macchiato())
print(Coffee.latte())</pre>
<p>This is called the <strong><em>factory pattern</em></strong>: the static methods are instance factories—they produce new instances according to their implementations. For example, the <code>Coffee.cappuccino()</code> method creates a special type of <code>Coffee</code> with an initial selection of 80% milk and Arrabica beans. </p>
<p>The output of this code snippet is:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Milk=80% Coffee=20% Beans=Arrabica
Milk=30% Coffee=70% Beans=Robusta
Milk=95% Coffee=5% Beans=Arrabica</pre>
<h2>Interactive Example Static Method</h2>
<p>The following interactive code shell allows you to play with this example and deepen your skills. </p>
<figure class="wp-block-image size-large"><a href="https://colab.research.google.com/drive/180nruovVbASJZvYnl5ITYf01onlVI8xl?usp=sharing" target="_blank" rel="noopener noreferrer"><img loading="lazy" width="1024" height="517" src="https://blog.finxter.com/wp-content/uploads/2020/12/image-55-1024x517.png" alt="" class="wp-image-18785" srcset="https://blog.finxter.com/wp-content/uploads/2020/12/image-55-1024x517.png 1024w, https://blog.finxter.com/wp-content/uplo...00x151.png 300w, https://blog.finxter.com/wp-content/uplo...68x388.png 768w, https://blog.finxter.com/wp-content/uplo...150x76.png 150w, https://blog.finxter.com/wp-content/uplo...age-55.png 1391w" sizes="(max-width: 1024px) 100vw, 1024px" /></a></figure>
<p><em><strong>Exercise</strong>: Can you create another coffee specialty?</em></p>
<h2>Static Method is a Function Decorator</h2>
<p>Decorators help to add functionality to existing code without having to modify the code itself. Decorators are so-called because they decorate code, they do not modify the code, but they make the code do different things using decoration. Now that we have understood closures, we can work our way step by step to understanding and using decorators.</p>
<p>The <code>@staticmethod</code> is a function decorator. It’s short for calling <code>staticmethod(m)</code> for the method <code>m</code> that you would decorate. </p>
<p>Here’s an example without using a decorator and by using <code>staticmethod()</code> instead:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">
class Coffee: def __init__(self, milk, beans): self.milk = milk # percentage self.coffee = 100-milk # percentage self.beans = beans def __repr__(self): return f'Milk={self.milk}% Coffee={self.coffee}% Beans={self.beans}' def cappuccino(): return Coffee(80, 'Arrabica') cappuccino = staticmethod(cappuccino) print(Coffee.cappuccino())</pre>
<p>The output is the same:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Milk=80% Coffee=20% Beans=Arrabica</pre>
<p>However, this is not the recommended way—use a decorator with the @ annotation instead!</p>
<p><strong>Related Article:</strong> <a href="https://blog.finxter.com/closures-and-decorators-in-python/" target="_blank" rel="noreferrer noopener" title="Closures and Decorators in Python">Decorators</a></p>
<h2>Static Method vs Instance Method</h2>
<p class="has-pale-cyan-blue-background-color has-background">If you don’t use the <code>@staticmethod</code> annotator, you obtain an instance method per default. The instance method requires that the first argument <code>self</code> is a reference to the instance itself on which the method is called. The static method doesn’t pass any implicit argument. Thus, the difference between static methods and instance methods is that Python passes nothing in the first case while passing the instance (object) as a first implicit argument in the second case.</p>
<p>Here’s a minimal example of a static and an instance method:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class C: @staticmethod def f(): print('hi') # instance method def g(self): None # call static method:
C.f() # call instance method:
C().g()</pre>
<h2>Static Method vs Class Method</h2>
<p class="has-pale-cyan-blue-background-color has-background">You may know static methods from programming languages such as C++ or Java. They’re methods that exist independently of whether or not you created an instance of the class. That’s why they don’t use any instance variable in the method body. If you want to use a static method in Python, you need to use the <code>@staticmethod</code> annotation rather than the <code>@classmethod</code> annotation. The difference is that static methods don’t expect a reference to either the instance or the class as an implied first argument. </p>
<p>Here’s an example comparing class methods, instance methods, and static methods:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">class C: @classmethod def f(cls): None # instance method def g(self): None @staticmethod def h(): None # call class method:
C.f() # call instance method:
C().g() # call static method:
C.h()
</pre>
<h2>Static Method vs Class Method vs Instance Method</h2>
<p>To summarize, here’s the difference between the three different types of methods:</p>
<ul>
<li>Static Methods,</li>
<li>Class Methods, and</li>
<li>Instance Methods.</li>
</ul>
<figure class="wp-block-table is-style-stripes">
<table>
<thead>
<tr>
<th></th>
<th>Instance Method</th>
<th>Class Method</th>
<th>Static Method</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Definition</strong></td>
<td><code>def f(self, arg1, arg2): ...</code></td>
<td><code>def f(cls, arg1, arg2): ...</code></td>
<td><code>def f(arg1, arg2): ...</code></td>
</tr>
<tr>
<td><strong>First Argument</strong></td>
<td>Reference to Instance</td>
<td>Reference to Class</td>
<td>No Reference</td>
</tr>
<tr>
<td><strong>Usage</strong></td>
<td>On instance: <code>C().f(arg1, arg2)</code></td>
<td>On class: <code>C.f(arg1, arg2)</code></td>
<td>On class: <code>C.f(arg1, arg2)</code></td>
</tr>
<tr>
<td><strong>Application</strong></td>
<td>Work on data of specific instance</td>
<td>Work independently of instance data—but depends on class (e.g., factory).</td>
<td>Work independent of instance data and class data (e.g., general computation)</td>
</tr>
</tbody>
</table>
</figure>
<h2>Related Video: Python Class Method</h2>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<div class="ast-oembed-container"><iframe title="Python classmethod() | A Helpful Guide" width="1400" height="788" src="https://www.youtube.com/embed/IBjwNReqxDc?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
</div>
</figure>
<h2>Summary</h2>
<p>Static methods are special cases of class methods. They’re bound to a class rather than an instance, so they’re independent on any instance’s state. </p>
<p>Python’s built-in function <code><code>staticmethod</code>()</code> prefixes a method definition as an annotation <code>@staticmethod</code>. This annotation transforms a normal instance method into a static method. </p>
<hr class="wp-block-separator"/>
<p>Do you want to boost your Python skills in a fun and easy-to-consume way? Consider the following resources and become a master coder!</p>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
<p>The post <a href="https://blog.finxter.com/python-staticmethod/" target="_blank" rel="noopener noreferrer">Python staticmethod()</a> first appeared on <a href="https://blog.finxter.com/" target="_blank" rel="noopener noreferrer">Finxter</a>.</p>
</div>


https://www.sickgaming.net/blog/2020/12/...ticmethod/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016