简体   繁体   中英

importing classes from a module in python

If I have a module called Physics with say, 4 classes written in it and I want to make objects with all these classes over in my main file, can I just do:

import Physics

or do I need to import each inidivual class by saying:

from Physics import ClassA  
from Physics import ClassB` 

and so on? I ask because I tried to just import the module name, but it would let me instantiate an object from one of the classes.

You can do any if the following:

from Physics import ClassA , ClassB
a = ClassA()
b = ClassB()
import Physics
a = Physics.ClassA()
b = Physics.ClassB()
from Physics import ClassA  
from Physics import ClassB
a = ClassA()
b = ClassB()
from Physics import *
a = ClassA()
b = ClassB()

Standard conventions usually prefer the first more than the others due to its conciseness while still being explicit.

There are lots of ways you can import things. If you plan on using something a lot and names within that module aren't common, you could do

from physics import *

or

from physics import ClassA, ClassB, ClassC

When you do this, you do not need to reference the module name when using the names from the module. Example:

object = ClassA()

If you are only using a few things from a module or the module has things that have common names (like exit() from sys that is like python's exit()) you might consider just importing the whole module so you can tell if it was from the module easily. However, when you do that you have to reference the module name each time you use the thing you want from that module.

import sys
sys.exit()

Some module names are longer and it can be annoying to type it out every time you use something from it. Because of that people often save the module imported to a variable:

import physics as phy
object = phy.ClassA()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM