Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a python module

Tags:

python

module

I create two files: test.py and test1234.py

test.py contains:

import test1234
t = test1234.test()

test1234.py contains:

class test():
    def __init__(self):

When put in the same directory, python test.py runs without error.

However, if I create a directory test1234 and put test1234.py and a blank init.py in this directory, python test.py gives the error:

AttributeError: 'module' object has no attribute 'test'

What do I need to do for test.py to be able to see the test class in test1234.py?

like image 361
Olhovsky Avatar asked Aug 08 '12 02:08

Olhovsky


People also ask

How to create a simple module in Python?

The simplest python module you can create is just a python file. Select a folder where you will be experimenting with modules. Then, create two files in it: fileA.py and fileB.py. Now, we can add a sample function inside fileA, which assumes the following content. print("Hurray!") def sample_function (): print ("Hurray!")

How do you name a Python module?

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Within a module, the module’s name (as a string) is available as the value of the global variable __name__.

How do I add a module to a Python module directory?

Since the sys.path is a Python list, we can append paths to it. We imported the sys module and appended our “modules” directory to it. So any time you need to import a module in the modules directory within this program, you can simply specify the name and you should be good to start working.

How to include a module or plugin in Python?

To include a module, it must be installed. Some modules comes already installed with Python, for all the others you need to use pip install. To create a plugin, you need to create two folders with the same name. In the sub-folder, put your module and an empty __init__.py file.


1 Answers

You have to import it through the package, or put it in __init__.py.

import test1234.test1234
t = test1234.test1234.test()
like image 74
Ignacio Vazquez-Abrams Avatar answered Oct 21 '22 07:10

Ignacio Vazquez-Abrams