Python from Keyword
Used importing from a module. Using from [module name] import [object name]
will import only one specific object in the Python module being imported. Importing modules makes the objects in those modules accessible to the module doing the import.
Python
Copy Code
from myModule import myClass
Example
Let's say you have a file called "moduleToImport.py" that looks like this:
Python
Copy Code
class FirstClass(): def sayHello(self): print('First class says hello.') class SecondClass(): def sayHello(self): print('Second class says hello.')
And we run this:
Python
Copy Code
from moduleToImport import FirstClass first = FirstClass() first.sayHello(); # We only imported FirstClass # If we try this, we get a "NameError: name 'SecondClass' is not defined # second = SecondClass() # second.sayHello()
Output
First class says hello.
You can specify more than one module name, separated by a comma.
Example
Python
Copy Code
from moduleToImport import FirstClass, SecondClass first = FirstClass() first.sayHello(); # Now we've imported both second = SecondClass() second.sayHello()
Output
First class says hello. Second class says hello.
You can alias the object names as well.
Example
Python
Copy Code
from moduleToImport import FirstClass as fc, SecondClass as sc first = fc() second = sc() first.sayHello(); second.sayHello()
Output
First class says hello. Second class says hello.