Python – Using Import Inside a Class

classimportpython

I am completely new to the python class concept. After searching for a solution for some days, I hope I will get help here:

I want a python class where I import a function and use it there. The main code should be able to call the function from the class. for that I have two files in the same folder.


Thanks to @cdarke, @DeepSpace and @MosesKoledoye, I edited the mistake, but sadly that wasn't it.

I still get the Error:

test 0
Traceback (most recent call last):
  File "run.py", line 3, in <module>
    foo.doit()
  File "/Users/ls/Documents/Entwicklung/RaspberryPi/test/test.py", line 8, in doit
    self.timer(5)
  File "/Users/ls/Documents/Entwicklung/RaspberryPi/test/test.py", line 6, in timer
    zeit.sleep(2)
NameError: global name 'zeit' is not defined


@wombatz got the right tip:
it must be self.zeit.sleep(2) or Test.zeit.sleep(2). the import could be also done above the class declaration.


Test.Py

class Test:
    import time as zeit
    def timer(self, count):
        for i in range(count):
            print("test "+str(i))
            self.zeit.sleep(2)      <-- self is importent, otherwise, move the import above the class declaration
    def doit(self):
        self.timer(5)

and

run.py

from test import Test
foo = Test()
foo.doit()

when I try to python run.py I get this error:

test 0
Traceback (most recent call last):
  File "run.py", line 3, in <module>
    foo.doit()
  File "/Users/ls/Documents/Entwicklung/RaspberryPi/test/test.py", line 8, in doit
    self.timer(5)
  File "/Users/ls/Documents/Entwicklung/RaspberryPi/test/test.py", line 6, in timer
    sleep(2)
NameError: global name 'sleep' is not defined

What I understand from the error is that the import in the class is not recognized. But how can I achive that the import in the class is recognized?

Best Answer

Everything defined inside the namespace of a class has to be accessed from that class. That holds for methods, variables, nested classes and everything else including modules.

If you really want to import a module inside a class you must access it from that class:

class Test:
    import time as zeit
    def timer(self):
        self.zeit.sleep(2)
        # or Test.zeit.sleep(2)

But why would you import the module inside the class anyway? I can't think of a use case for that despite from wanting it to put into that namespace.

You really should move the import to the top of the module. Then you can call zeit.sleep(2) inside the class without prefixing self or Test.

Also you should not use non-english identifiers like zeit. People who only speak english should be able to read your code.