Import function in class python

If, like me, you want to make a function pack or something that people can download then it's very simple. Just write your function in a python file and save it as the name you want IN YOUR PYTHON DIRECTORY. Now, in your script where you want to use this, you type:

from FILE NAME import FUNCTION NAME

Note - the parts in capital letters are where you type the file name and function name.

Now you just use your function however it was meant to be.

Example:

FUNCTION SCRIPT - saved at C:\Python27 as function_choose.py

def choose[a]:
  from random import randint
  b = randint[0, len[a] - 1]
  c = a[b]
  return[c]

SCRIPT USING FUNCTION - saved wherever

from function_choose import choose
list_a = ["dog", "cat", "chicken"]
print[choose[list_a]]

OUTPUT WILL BE DOG, CAT, OR CHICKEN

Hoped this helped, now you can create function packs for download!

--------------------------------This is for Python 2.7-------------------------------------

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    In this article, we will see How to import a class from another file in Python.

    Import in Python is analogous to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. The import statement is that the commonest way of invoking the import machinery, but it’s not the sole way. The import statement consists of the import keyword alongside the name of the module.

    Getting Started

    Here we have created a class named GFG which has two methods: add[] and sub[]. Apart from that an explicit function is created named method[] in the same python file. This file will act as a module for the main python file.

    Python

    class GFG:

        def add[self, a, b]:

            return a + b

        def sub[self, a, b]:

            return a - b

    def method[]:

        print["GFG"]

    Let the name of the above python file be module.py.

    Importing

    It’s now time to import the module and start trying out our new class and functions. Here, we will import a module named module and create the object of the class named GFG inside that module. Now, we can use its methods and variables.

    Python

    import module

    object = module.GFG[]

    print[object.add[15,5]]

    print[object.sub[15,5]]

    module.method[]

    Output:

    20
    10
    GFG

    Importing the module as we mentioned earlier will automatically bring over every single class and performance within the module into the namespace. If you’re only getting to use one function, you’ll prevent the namespace from being cluttered by only importing that function as demonstrated in the program below:

    Python

    from module import method

    method[]

    Output:

    GFG

    In this way, we can use class to import from another file.


    In this article, we will understand the need for modular programming and then will learn how to Import Classes from another file in the python programming language. We will discuss some examples to understand them more clearly. We will also understand how predefined libraries help us. So let’s get started.

    • Why is it needed?
    • Object Oriented Programming or OOPs
    • Modular Programming
      • Advantage of using Modular Programming
    • Introduction to Import statement
    • Import Classes From Another File
    • Import All classes from Another File
    • Import Classes From Another Folder
    • Import Classes From Predefined Libraries
    • FAQs
    • Conclusion
    • Trending Python Articles

    Why is it needed?

    So, the first question that sounds to our mind is that why we need to import any file or classes from another file? Or, Is it really important? 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 we have to repeat certain operations. Writing code for them each and every time 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 real-time entities like inheritance [ i.e. inheriting properties from other classes], abstraction [ i.e. information hiding], polymorphism [i.e. present in many forms] e.t.c. in it. It is an independent concept in itself, so we will talk about it somewhat later. For now, move ahead and talk about modular programming.

    Modular Programming

    Although, OOPs is an efficient and smart way of programming, we can’t say that it themselves solve all the problems alone. Besides the core concept of OOPs, there are some other problems we face while programming. Working on real scenarios is very different from the one that we learn. In reality, solving any problem may require thousands of lines of codes which may have hundreds of functions and tens of classes. Maintaining all those functions and classes in one program is a difficult task. So 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 problem, we split it 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 can increase the readability of codes. We can reuse it a number of times. More, it is easy for us to maintain them and make changes to them according to our use. Moreover, it helps us a lot while debugging our program as we don’t have to fumble much in one file.

    Introduction to Import statement

    Once all independent problems are solved, the question arises that how can we associate them. Here, the Python Import statement comes into the picture.

    Import statement helps in importing code from other files or modules into the file we are working on. You can think of it as a bridge that gives us access to the class attributes or methods from other files so that we can use them. However, there is a proper syntax to follow to do that which we will see in a few seconds. Before that first 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 folder that contains two folders named module1 and module2. Inside each folder, we have files named file1, file2, and file3 respectively. Now, we will discuss different scenarios of importing classes or files one by one. Here we go,

    In this example, first, we will define a class in file1.py and then import it in file2.py.

    application/module1/file1.py

    class ArithmeticOperations:
    
        def __init__[self]:
            self.sum_ = 0
        
        def get_sum[self,num1,num2]:
            self.sum_ = num1+num2
            return self.sum_
    
    

    application/module1/file2.py

    import file1
    
    obj = file1.ArithmeticOperations[]
    c = obj.get_sum[3,8]
    print[c]
    

    Output: 
    11

    In the above example, we imported file1 using the “import” statement. After that, we create an instance of the class we want to use i.e. ArithmeticOperations by referring to it. We can understand it as;

    • We imported the file named file1.
    • After that we refer that class using file1.ArithmeticOperations[] and assign it to variable obj.
    • After that we call get_sum function by using ‘obj’ object.
    • And, then print the result assigned in ‘c‘ variable.

    We can also do it using “from import ” statement. Take a look to it;

    from file1 import ArithmeticOperations
    
    obj = ArithmeticOperations[]
    print[obj.get_sum[9,11]]
    

    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 use “from import *” statement. We can read it as from file_name import all. It means that we imported all the available classes from the given file. Let’s look at its example.

    application/module1/file1.py

    class ArithmeticOperations:
    
        def __init__[self]:
            self.sum_ = 0
        
        def get_sum[self,num1,num2]:
            self.sum_ = num1+num2
            return self.sum_
    
    class PrintData:
    
        def __init__[self]:
            self.data = ""
    
        def print_data[self,data]:
            self.data = data
            return self.data
    
        
    

    application/module1/file2.py

    from file1 import *
    
    obj1 = ArithmeticOperations[]
    print[obj1.get_sum[9,11]]
    
    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 class 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 within the same package.

    We also have to specify the path of module1. For that, we will use the “sys” module. Let’s 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 code tells the interpreter that first come out of the current directory to parent directory and then look for the module there.

    Import Classes From Predefined Libraries

    In the above example, we used “import sys” which is a predefined library and we want to import it and use its functionalities.

    sys.path.insert[]; We can understand, that we want to use the insert method from the path class that is present in the sys module. Using such dependencies and modules make our works easier as we don’t need to write code for those function explicitly. We just need the knowledge of the given package 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 want to import. The answer to this question depends on various conditions in which you want to import the file. We have discussed all of the above and you can refer to them according to your condition.

    How to use __import__ to import a class from other files in Python?

    We can use the following code in file2.py to import the class from file1 dynamically.

    class 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[data]

    obj = Dynamic_import[“file1″,”ArithmeticOperations”]

    How to import class dynamically?

    We can import class dynamically using __import__ magic function or imp module.
    See it with an example;

    import imp
    import sys

    #dynamic import
    def dynamic_imp[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 class or package
    package = imp.load_module[name, fp, path, desc]
    class_ = imp.load_module["% s.% s" % [name, class_name], fp, path, desc]
    return package, class

    if name == “main“:
    mod, modCl = dynamic_imp[“file1 “,”addNumbers”]
    modCl.addNumbers[1, 2]

    How do I import a class from another Jupyter notebook?

    # Run the following command
    !pip install ipynb

    # You can import other notebooks using
    from ipynb.fs.full. import *

    Conclusion

    So, today we looked at how can we 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 made it easier.

    I hope this article helped you. Keep supporting. Thank You!

    Trending Python Articles

    • How To Convert PIL Images to Numpy Array

      September 10, 2022

    • The A-Z of Python Virtualenv Location

      by Vishnu VenkateshSeptember 8, 2022

    • How To Solve Error: legacy-install-failure?

      by Yugmil PatelSeptember 6, 2022

    • 6 Methods To Tokenize String In Python

      by Yugmil PatelSeptember 6, 2022

    Can you import into a class Python?

    Importing a specific class by using the import command You just have to make another . py file just like MyFile.py and make the class your desired name. Then in the main file just import the class using the command line from MyFile import Square.

    Can you import a function in Python?

    Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way.

    What is __ import __ in Python?

    __import__[] . This means all semantics of the function are derived from importlib. __import__[] . The most important difference between these two functions is that import_module[] returns the specified package or module [e.g. pkg. mod ], while __import__[] returns the top-level package or module [e.g. pkg ].

    How do I call a class method from another file in Python?

    Create a Python file containing the required functions. Create another Python file and import the previous Python file into it. Call the functions defined in the imported file.

    Chủ Đề