Well, it is not that simple.
Actually, import statement in many aspects looks like direct definition of something in place of it. If you write
class test:
from platform import system
it looks exactly like
class test:
def system():
# ....
and then you have following problems:
- you can't use just system() because system is not in global scope
- you can't use self.system() because in this form, python automatically passes
self
as first argument, but system() has no parameters and you'll get TypeError: system() takes no arguments (1 given)
- you can't use test.system() because system() looks like a plain method, and you'll get
TypeError: unbound method system() must be called with test instance as first argument (got nothing instead)
There are several ways around these problems:
- place
import platform
at top level, and use platform.system() wherever you want, thus fixing issue #1 from prev. list
- use
staticmethod
decorator, fixing issues #2 and #3 from prev. list.
like
class test:
from platform import system
system = staticmethod(system)
then you can use either self.system() or test.system()
Actually, you should just import everything in toplevel and forget about it.
You only have to split import declarations if you need something special for running.
Like
import foo
import bar
def fun(param1, param2):
# .....
if __name__ == '__main__':
from sys import argv
if len(argv) > 2:
fun(argv[1], argv[2])
In this example, moving from sys import argv
is valid, because it is needed only when running a script. But when you use it as an imported module, there is no need in this import.
But that is not your case, because in your case, system() is always needed for test class, so there is no reason to move this import from toplevel. Just leave it there and never mind.