Dynamic typing

from Wikipedia, the free encyclopedia

Dynamic typing (English. Dynamic typing ) refers to a scheme of typing of programming languages .

With dynamic typing, type tests (e.g. the data type of variables) take place primarily during the runtime of a program . In contrast, with static typing, the type check is carried out at the time of compilation .

Scripting languages such as JavaScript , Python, and Ruby use dynamic typing.

Examples

python

Here is an interactive Python session:

>>> a = 1                         # a enthält durch Zuweisung eine ganze Zahl
>>> a += 1.0                      # addiert die Gleitkommazahl 1.0 und legt neuen Wert (mit anderem Typ) in a ab
>>> a.upper()                     # Scheitert: a ist keine Zeichenkette
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'float' object has no attribute 'upper'
>>> a                             # gibt den Wert von a aus
2.0
>>> a = "jetzt ist a ein String"
>>> a += 1                        # Scheitert: Inhalt von a ist jetzt ein String
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>> a.upper()
'JETZT IST A EIN STRING'

In Python, variables have no type, only the objects to which the variables reference. The error message “has no attribute 'upper'” illustrates that the Python interpreter does not necessarily require a string, but would be satisfied with any object with an upper method (see Duck Typing ).

Boo

Example from the project page

 1 d as duck
 2 
 3 d = 5           // Derzeitig als Integer definiert.
 4 print d
 5 d += 10         // Es kann alles, was ein Integer kann.
 6 print d
 7 d = "Hi there"  // Wird zu einem String gesetzt.
 8 print d
 9 d = d.ToUpper() // Jetzt kann es alles, was ein String kann.
10 print d

Output:

5
15
Hi there
HI THERE

Explanation of the example

The variable d is created and the data type duck is assigned to it. This is not a real data type, just a kind of container that can accept other data types. In the third line, d is assigned the integer value 5 .

In line 7 the string Hi there is assigned. In other programming languages ​​such as C # or C ++ this would now lead to a compiler error.

The Boo Compiler, on the other hand, recognizes from the data type duck that the data type of the variable d can change.

See also

Individual evidence

  1. Boo project page ( Memento of the original from February 3, 2007 in the Internet Archive ) Info: The archive link was automatically inserted and not yet checked. Please check the original and archive link according to the instructions and then remove this notice. , As of April 19, 2006, 7:52 p.m. @1@ 2Template: Webachiv / IABot / boo.codehaus.org