Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Define A Method Outside Of The Class Definition

#1
Define A Method Outside Of The Class Definition

<div><div id="ez-toc-container" class="ez-toc-v2_0_17 counter-hierarchy counter-decimal ez-toc-light-blue">
<div class="ez-toc-title-container">
<p class="ez-toc-title">Table of Contents</p>
<p><span class="ez-toc-title-toggle"><a class="ez-toc-pull-right ez-toc-btn ez-toc-btn-xs ez-toc-btn-default ez-toc-toggle" style="display: none;"><i class="ez-toc-glyphicon ez-toc-icon-toggle"></i></a></span></div>
<nav>
<ul class="ez-toc-list ez-toc-list-level-1">
<li class="ez-toc-page-1 ez-toc-heading-level-2"><a class="ez-toc-link ez-toc-heading-1" href="https://blog.finxter.com/define-a-method-outside-of-the-class-definition/#Introduction" title="Introduction">Introduction</a></li>
<li class="ez-toc-page-1 ez-toc-heading-level-2"><a class="ez-toc-link ez-toc-heading-2" href="https://blog.finxter.com/define-a-method-outside-of-the-class-definition/#Define_The_Method_Outside_and_Use_Inside_Class_Body" title="Define The Method Outside and Use Inside Class Body">Define The Method Outside and Use Inside Class Body</a></li>
<li class="ez-toc-page-1 ez-toc-heading-level-2"><a class="ez-toc-link ez-toc-heading-3" href="https://blog.finxter.com/define-a-method-outside-of-the-class-definition/#Using_Inheritance" title="Using Inheritance">Using Inheritance</a></li>
<li class="ez-toc-page-1 ez-toc-heading-level-2"><a class="ez-toc-link ez-toc-heading-4" href="https://blog.finxter.com/define-a-method-outside-of-the-class-definition/#Conclusion" title="Conclusion">Conclusion</a></li>
</ul>
</nav>
</div>
<p><strong>Problem Statement:</strong> How to define a method outside of class definition in Python?</p>
<p><strong>Example:</strong></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=""># Given Class
class Demo:
# Given Method def foo(self): x = 10 return x</pre>
<p>Can we create <code>foo()</code> outside of the class definition or maybe even in another module?</p>
<h2><strong>Introduction</strong></h2>
<p>We all know Python is an object-oriented programming language, and in Python, everything is an object including properties and methods. In Python, the class is like an object’s constructor for creating the objects. Thus, the variables can be defined inside the class, outside the class, and inside the methods in Python. The variables defined outside the class can be accessed by any method or class by just writing the variable name. So, in this article, we are going to learn how to define a method outside of the class definition.</p>
<p><strong>What are Methods in Python?</strong></p>
<p>As Python is an object-oriented programming language, it has objects that consist of properties. The attributes define the properties of these objects, and the behavior is defined using methods. Methods are reusable pieces of code called at any point in the program and are defined inside the class. Every method is associated with the class and can be invoked on the instances of that class.</p>
<p>For example, we can consider a class named ‘<code>Students</code>’ that contains properties like <code>name</code>, <code>id </code>, and <code>rank</code>. The class also holds behaviors like <code data-enlighter-language="generic" class="EnlighterJSRAW">run</code>, <code data-enlighter-language="generic" class="EnlighterJSRAW">jump </code>, and <code data-enlighter-language="generic" class="EnlighterJSRAW">swim</code>. Suppose an object <code>Stud1</code> has the following properties:</p>
<pre class="wp-block-code"><code>Name- Finxter
Id – 1020
Rank- 1
</code></pre>
<p>Here’s how you can assign the values:</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 Student: def __init__(self, name, id, rank): self.name = name self.id = id self.rank = rank def run(self): print(f'{self.name} is a cross country champion!') def jump(self): print(f'{self.name} with the following ID: {self.id} is a high jumper!') def swim(self): print(f'{self.name} secured rank {self.rank} in swimming.') stud1 = Student('Finxter', 1020, 1)
stud1.run()
stud1.jump()
stud1.swim()</pre>
<p><strong>Output:</strong></p>
<pre class="wp-block-code"><code>Finxter is a cross country champion!
Finxter with the following ID: 1020 is a high jumper!
Finxter secured rank 1 in swimming.</code></pre>
<p>The above example demonstrated the traditional way of adding functionality (methods) to a Python class. Here, the methods were defined inside the class body. Now, let’s say that you want to define a method outside the class body. How will you do so? Let’s dive into the different approaches to unearth the answers to this question.</p>
<h2><strong>Define The Method Outside and Use Inside Class Body</strong></h2>
<p>The idea here is to define the method outside the class and then use it inside the class body, as shown below.</p>
<p><strong>Example 1:</strong></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=""># Defining the method outside the class
def foo(self): print("Method foo executed") x = 10 print("Value of x = ", x)
# Using the method inside the class body
class Demo: my_method = foo</pre>
<p>You can also define a class first and then add a method or function to it from outside its body, as shown below.</p>
<p><strong>Example 2:</strong></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=""># Define the class
class Demo: pass # Define the method outside the class def foo(self): print("Method foo executed ") # Pass the method to the class
Demo.method1 = foo</pre>
<p><strong>Caution: </strong>We can even define the functions, methods, and classes in different modules if we want to. However, it is advisable to use example 1 rather than example 2 (defining the class in one module, then importing it into another module and further adding methods to it dynamically) because the class objects may behave differently depending on whether the module has been imported or not.</p>
<p>There’s another way to define the function outside of a class and then further add it. But there is a difference in assigning the function to the instance object or the class. Look at the following example to understand the subtle difference:</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 Demo1(object): def __init__(self, bar): self.func = 'Finxter' Demo1.funcbar = bar class Demo2(object): def __init__(self, bar): self.func = 'Finxter' self.funcbar = bar def bar(self): return 'Welcome' + self.func</pre>
<p><strong>Explanation: </strong>Let’s understand what’s happening here. </p>
<ul>
<li>In case of class <code>Demo1</code> , <code>funcbar</code> is just like any other normal method that is <strong>bound </strong>to the instance of the class. Let’s have a look at what this looks like –</li>
</ul>
<figure class="wp-block-image size-full is-style-default"><img loading="lazy" width="877" height="648" src="https://blog.finxter.com/wp-content/uploads/2022/03/image-244.png" alt="" class="wp-image-269572" srcset="https://blog.finxter.com/wp-content/uploads/2022/03/image-244.png 877w, https://blog.finxter.com/wp-content/uplo...00x222.png 300w, https://blog.finxter.com/wp-content/uplo...68x567.png 768w" sizes="(max-width: 877px) 100vw, 877px" /></figure>
<ul>
<li>In case of class <code>Demo 2</code>, <code>funcbar</code> is simply a reference to the bar function, i.e., it is <strong>not a</strong> <strong>bound function.</strong> Thus, we must pass the instance for this function for it to work properly.</li>
</ul>
<figure class="wp-block-image size-full is-style-default"><img loading="lazy" width="598" height="645" src="https://blog.finxter.com/wp-content/uploads/2022/03/image-246.png" alt="" class="wp-image-269574" srcset="https://blog.finxter.com/wp-content/uploads/2022/03/image-246.png 598w, https://blog.finxter.com/wp-content/uplo...78x300.png 278w" sizes="(max-width: 598px) 100vw, 598px" /></figure>
<h2><strong>Using <a href="https://blog.finxter.com/inheritance-in-python-harry-potter-example/" target="_blank" rel="noreferrer noopener">Inheritance</a></strong></h2>
<p>You can even use the methods of a class in another class. In the following example we have a class <code>Helper</code> with certain methods defined within it. All the methods of the class <code>Helper</code> can be inherited by the class <code>Demo </code>as shown below.</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 Helper(object): # Subtraction function def subs(self, a, b): return a - b # Addition function def add(self, a, b): return a + b # Multiplication function def mul(self, a, b): return a * b # Division function def div(self, a, b): return a / b
# Given class
class Demo(Helper): def __init__(self): Helper.__init__(self) print("The addition of numbers is", self.add(10, 5)) print("Subtraction of numbers is", self.subs(60, 15)) print("Multiplication of numbers is", self.mul(5, 9)) print("The division of numbers is", self.div(100, 50))
# Main method
if __name__ == '__main__': obj = Demo()</pre>
<p><strong>Output:</strong></p>
<pre class="wp-block-code"><code>The addition of numbers is 15
Subtraction of numbers is 45
Multiplication of numbers is 45
The division of numbers is 2.0</code></pre>
<p class="has-base-background-color has-background"><strong>Related Read: <a href="https://blog.finxter.com/inheritance-in-python-harry-potter-example/" target="_blank" rel="noreferrer noopener">Inheritance in Python</a></strong></p>
<h2><strong>Conclusion</strong></h2>
<p>To sum things up, it is absolutely possible to have functions outside classes in Python. If you want to gather a group of functions in one box then you can simply put them together in the same module. Further, you can nest modules within packages. It is recommended that you should use classes when you have to create a new datatype and don’t just use it to group functions together. </p>
<p>That’s it for this discussion and I hope it helped you. Please stay tuned and subscribe for more interesting articles and discussions in the future. Happy learning! </p>
<hr class="wp-block-separator is-style-wide" />
<p class="has-text-align-center has-base-2-background-color has-background" style="font-size:15px">Article by <strong>Shubham Sayon and Rashi Agarwal</strong></p>
</div>


https://www.sickgaming.net/blog/2022/03/...efinition/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016