using import inside class

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.

Leave a Comment