from import导入变量

├── __init__.py
├── __pycache__
│   ├── c1.cpython-38.pyc
│   └── c2.cpython-38.pyc
├── c1.py
├── c2.py
├── c4.py
└── t
    ├── __pycache__
    │   └── c3.cpython-38.pyc
    └── c3.py

语法

from module import 变量a, 函数def

c4.py

from t.c3 import a

print(a) # 2

from 也可以引入模块

from t import c3
print(c3.a) #2

假如c3.py有很多东西要引入,如何一次性全部引入呢?

c3.py

a = 2
b = 3
c = 4

c4.py

from t.c3 import *
print(a) #2
print(b) #3
print(c) #4

如何定向的导出特定的变量?

改写 c3.py

__all__ = ['a','b'] # __all__叫做模块的内置变量, 只导出变量 a b,那么如果你在外界访问c就会报错

a = 2
b = 3
c = 4

c4.py

from t.c3 import *
print(a) #2
print(b) #3
print(c) # 报错
2
3
Traceback (most recent call last):
  File "/Users/scottxiong/Desktop/end/python/c4.py", line 5, in <module>
    print(c)
NameError: name 'c' is not defined

results matching ""

    No results matching ""