BeginPackage
Usage
• BeginPackage["context`"] 使得 context` 和System`是仅有的活动上下文。
• BeginPackage["context`", " `", " `", ... ] 调用  中的 Needs。
Notes
• BeginPackage 通常用在包的开头。 • BeginPackage 重新设置 $Context 和 $ContextPath的值。 • 符号名的解释与上下文有关。这样BeginPackage 影响输入表达式的分析。 • 参见 Mathematica 全书: 节 2.6.10.
Further Examples
BeginPackage sets things up so that only System` and the named context are in the context search path. As a result, any reference to something other than a predefined symbol creates a new symbol in the named context.
In[1]:=
|
Out[1]=
|
The corresponding EndPackage restores the earlier environment, and also adds to the $ContextPath the context that's being concluded. As a result, symbols created between the invocations of BeginPackage and EndPackage are now accessible under their short names.
In[2]:=
|
Out[2]=
|
A package often needs to use variables and functions that should not be accessible by their short names ("private" symbols). Such symbols are traditionally created inside a subcontext of the context created by BeginPackage. Here is a full example illustrating the standard sequence of context control commands. This makes Collatz` the current context, and puts only System` on the context search path.
In[3]:=
|
Out[3]=
|
This introduces the objects intended to be "exported", that is, made visible after the package is loaded.
In[4]:=
|
This passes to a subcontext. The backquote at the beginning of `Private` stands for the current context.
In[5]:=
|
Out[5]=
|
Here is the definition of the function.
In[6]:=
|
This tells Mathematica to revert to the previous context (here, Collatz`).
In[7]:=
|
Out[7]=
|
This ends the package, prepending Collatz` to the context search path.
In[8]:=
|
Here is the context search path.
In[9]:=
|
Out[9]=
|
The Collatz function was created in the context Collatz`.
In[10]:=
|
Out[10]=
|
The symbol n was put in the private context Collatz`Private`. It is not accessible by its short name, so it won't interfere with other uses for n.
In[11]:=
|
|