12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Python</strong> to use the name a as a variable, or that a should stand for an integer-typeobject. In the <strong>Python</strong> language, this all pans out in a very natural way, as follows:Variable creationA variable (i.e., name), like a, is created when your code first assigns it a value.Future assignments change the value of the already created name. Technically,<strong>Python</strong> detects some names before your code runs, but you can think of it asthough initial assignments make variables.Variable typesA variable never has any type information or constraints associated with it. Thenotion of type lives with objects, not names. Variables are generic in nature; theyalways simply refer to a particular object at a particular point in time.Variable useWhen a variable appears in an expression, it is immediately replaced with theobject that it currently refers to, whatever that may be. Further, all variablesmust be explicitly assigned before they can be used; use of unassigned variablesresults in errors.This model is strikingly different from traditional languages. When you are first startingout, dynamic typing is usually easier to understand if you keep clear the distinctionbetween names and objects. For example, when we say this:>>> a = 3at least conceptually, <strong>Python</strong> will perform three distinct steps to carry out therequest. These steps reflect the operation of all assignments in the <strong>Python</strong> language:1. Create an object to represent the value 3.2. Create the variable a, if it does not yet exist.3. Link the variable a to the new object 3.The net result will be a structure inside <strong>Python</strong> that resembles Figure 6-1. Assketched, variables and objects are stored in different parts of memory, and are associatedby links (the link is shown as a pointer in the figure). Variables always link toobjects, and never to other variables, but larger objects may link to other objects (forinstance, a list object has links to the objects it contains).Names References Objectsa 3Figure 6-1. Names and objects, after running the assignment a = 3. Variable a becomes a referenceto object 3. Internally, the variable is really a pointer to the object’s memory space created byrunning literal expression 3.The Case of the Missing Declaration Statements | 113

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!