banner



Kotlin Import Class From Another File

In this article, we will sympathise the need for modular programming and then volition learn how to Import Classes from another file in the python programming language. We will discuss some examples to understand them more conspicuously. We will besides empathize how predefined libraries assistance united states. So allow'due south get started.

Why is it needed?

So, the first question that sounds to our heed is that why we demand to import whatever file or classes from some other file? Or, Is it actually of import? Or, How it will affect our programming approach? Answers to all these questions are within this article.

First, understand why is it needed? In programming, we are often in situations in which nosotros have to repeat certain operations. Writing code for them each and every fourth dimension is quite a tedious task. To avoid such situations, we use the concept of Object-Oriented Programming aka OOPs.

Object Oriented Programming or OOPs

OOPs is a programming concept in which we create objects based on some defined classes having some properties (called attributes) and functions (called methods). The advantage of doing that is we can reuse it a number of times we want. We can also implement other existent-time entities similar inheritance ( i.eastward. inheriting properties from other classes), abstraction ( i.e. information hiding), polymorphism (i.eastward. present in many forms) e.t.c. in information technology. It is an contained concept in itself, so we volition talk almost it somewhat after. For at present, move ahead and talk well-nigh modular programming.

Modular Programming

Although, OOPs is an efficient and smart style of programming, we can't say that it themselves solve all the problems lonely. Besides the core concept of OOPs, at that place are some other problems we face while programming. Working on real scenarios is very different from the 1 that we learn. In reality, solving whatever problem may require thousands of lines of codes which may accept hundreds of functions and tens of classes. Maintaining all those functions and classes in one program is a hard task. And then we use the modular programming approach to cope with such situations.

Modular Programming is a programming approach in which rather than writing code for one big trouble, we split information technology into several small independent problems. Once we solve each of them, we unite them to achieve our primary goal.

Advantage of using Modular Programming

The advantage of following the approach is that we tin increase the readability of codes. Nosotros can reuse information technology a number of times. More, it is like shooting fish in a barrel for u.s. to maintain them and make changes to them according to our use. Moreover, it helps us a lot while debugging our programme as we don't have to fumble much in one file.

Introduction to Import statement

One time all independent problems are solved, the question arises that how can we associate them. Hither, the Python Import argument comes into the picture.

Import statement helps in importing code from other files or modules into the file nosotros are working on. You can recollect of it as a bridge that gives us admission to the class attributes or methods from other files and then that nosotros tin can use them. Nevertheless, there is a proper syntax to follow to practise that which nosotros will come across in a few seconds. Before that showtime understand the given directory structure.

                      application   |   |---- module1   |       |------- __init__.py   |       |------- file1.py   |       |------- file2.py   |   |---- module2           |------- file3.py                  

So, in the given directory structure we have an application binder that contains two folders named module1 and module2. Inside each binder, we have files named file1, file2, and file3 respectively. At present, nosotros will discuss different scenarios of importing classes or files one by 1. Here nosotros go,

Import Classes From Another File

In this example, offset, we will define a form in file1.py and then import information technology in file2.py.

          application/module1/file1.py        
class ArithmeticOperations:      def __init__(self):         self.sum_ = 0          def get_sum(cocky,num1,num2):         self.sum_ = num1+num2         render self.sum_          
          application/module1/file2.py        
import file1  obj = file1.ArithmeticOperations() c = obj.get_sum(iii,8) print(c)          
          Output:  11        

In the above example, nosotros imported file1 using the "import" statement. Later that, we create an case of the form nosotros want to use i.e. ArithmeticOperations past referring to information technology. We can understand it as;

  • Nosotros imported the file named file1.
  • Later on that we refer that class using file1.ArithmeticOperations() and assign it to variable obj.
  • After that nosotros call get_sum function by using 'obj' object.
  • And, and so print the effect assigned in 'c' variable.

We can also do it using "from <module_name> import <class_name> " statement. Accept a look to information technology;

from file1 import ArithmeticOperations  obj = ArithmeticOperations() impress(obj.get_sum(9,xi))          
          Output: 20        

Import All classes from Another File

In this section, we will discuss that can we import all the classes at once from another file. Sometimes, it is the scenario that it is needed to import all the classes from other files. In that case, we utilise "from <file_name> import *" argument. Nosotros can read it as from file_name import all. It means that nosotros imported all the available classes from the given file. Allow's await at its instance.

          application/module1/file1.py        
class ArithmeticOperations:      def __init__(self):         self.sum_ = 0          def get_sum(cocky,num1,num2):         self.sum_ = num1+num2         return self.sum_  class PrintData:      def __init__(cocky):         self.information = ""      def print_data(self,information):         self.information = data         return cocky.data          
          application/module1/file2.py        
from file1 import *  obj1 = ArithmeticOperations() print(obj1.get_sum(ix,xi))  obj2 = PrintData() print(obj2.print_data("Accessing Another class from file1"))          
          Output: 20 Accessing Another class from file1        

Import Classes From Another Folder

In this example, we will use ArithmeticOperations grade in file3.py i.e located in another folder i.e module1. But before doing that we have to include __init__.py file in module1 which tells the interpreter that the module is inside the same package.

Nosotros also take to specify the path of module1. For that, we will use the "sys" module. Permit'due south look at the code.

import sys sys.path.insert(0,"..")  from module1.file1 import ArithmeticOperations   obj = ArithmeticOperations() print(obj.get_sum(8,23))          
          Output: 31        

'sys.path.insert(0,"..") ' This line of lawmaking tells the interpreter that start come up out of the electric current directory to parent directory and then expect for the module there.

Import Classes From Predefined Libraries

In the to a higher place example, we used "import sys" which is a predefined library and we want to import it and utilize its functionalities.

sys.path.insert(); Nosotros can empathise, that we want to utilize the insert method from the path grade that is present in the sys module. Using such dependencies and modules make our works easier equally we don't need to write code for those office explicitly. We but need the knowledge of the given bundle and how to use it.

FAQs

Python import class from another file not working

In this case, the issue lies within the reference of the source class you desire to import. The answer to this question depends on various weather in which you lot want to import the file. We have discussed all of the above and you tin can refer to them according to your status.

How to employ __import__ to import a course from other files in Python?

Nosotros can use the following code in file2.py to import the course from file1 dynamically.

form Dynamic_import:

def __init__(self,module_name,class_name):

#__init__ method is used to import the module which takes module name as the parameter
module = __import__(module_name)

# getattr() is used to import class name form the module we imported
class_nm = getattr(module,class_name)
data= class_nm.get_sum(class_nm,3,8)
print(information)

obj = Dynamic_import("file1″,"ArithmeticOperations")

How to import class dynamically?

We tin import class dynamically using __import__ magic function or imp module.
Meet information technology with an example;

import imp
import sys

#dynamic import
def dynamic_imp(proper name, class_name):
# imp.find_module() returns the path and description of given module
fp, path, desc = imp.find_module(name)

#imp.load_module() returns either form or package
packet = imp.load_module(name, fp, path, desc)
class_ = imp.load_module("% s.% s" % (name, class_name), fp, path, desc)
return parcel, course

if name == "main":
modern, modCl = dynamic_imp("file1 ","addNumbers")
modCl.addNumbers(i, ii)

How practise I import a grade from another Jupyter notebook?

# Run the post-obit command
!pip install ipynb

# Y'all can import other notebooks using
from ipynb.fs.full.<notebook> import *

Conclusion

So, today nosotros looked at how can nosotros import classes from other files or folders. We also gained knowledge about Modular Programming and Import Statement. We looked, Modular programming changed the approach of programming and fabricated it easier.

I hope this commodity helped you. Keep supporting. Thanks!

Source: https://www.pythonpool.com/import-classes-from-another-file-in-python/

0 Response to "Kotlin Import Class From Another File"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel