1

I am trying to understand classes and I cannot access to class in different file. What I want to do: I have to files aaaa.py and unittest.py in folder temp. aaaa.py:

class Test:

    def __init__(self):
        print('Test')

    def function(self):
        print('Test3')

unittest.py:

import temp.aaaa

y = temp.aaaa.Test()

when I run unittest I get error:

AttributeError: module 'temp' has no attribute 'aaaa'

what is the problem?

edit: project structure:

->Project:
--> temp:
---> extr(folder)
---> __init__.py
---> aaaa.py
---> unittest.py
---> test.txt
pyton17
  • 55
  • 10

3 Answers3

0

To saying to Python that "temp" folder contains .py that you want to import you have to create a __init__.py file inside the "temp" folder.

What is __init__.py for?

0

You have to do something like:

First solution:

from aaaa import Test
x = Test()

Second solution:

from temp import aaaa
x= aaaa.Test()

Hope this helps!

SLake
  • 24
  • 5
0

I'm assuming your filestructure is akin to the following:

root_package/
 |_ __init__.py
 |_ unittest.py
 |_ aaaa.py

In python3 you can no longer use implict relative imports, for example in unittest.py:

# not valid, implicit relative import
import aaaa 

# valid, explicit relative import
from . import aaaa 

# valid, absolute import
from root_package import aaaa

Whether you use absolute imports or explicit relative imports is a style question that still rages :)

ptr
  • 3,292
  • 2
  • 24
  • 48
  • I did like this: from temp import aaaa in aaaa I have class Test. And when I am using this 'y = aaaa.Test()' I am getting error: AttributeError: module 'temp.aaaa' has no attribute 'Test' – pyton17 May 17 '18 at 08:19
  • could you please add the output of `print(dir(aaaa))` above the line `y = aaaa.Test()` ? – ptr May 17 '18 at 08:24
  • ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'csv', 'json'] ['StaticRecon', 'Test', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'collections', 'csv', 'json', 'unittest'] – pyton17 May 17 '18 at 08:26
  • Why are there two lists? `dir(aaaa)` should return one list of all the attributes available in the `aaaa.py` module – ptr May 17 '18 at 08:31