Simple Type
The simple data types built into the Python programming language include:
bool
Int
Float
Complex
Supporting simple data types is not a unique feature of Python, because most modern programming languages have complete type supplements. such as Java? The language even has a richer set of original data types:
Byte
Short
Int
Long
Float
Double
Char
Boolean
In Python, however, simple data types are not raw data types, but perfect objects that have their own methods and classes. In addition, these simple built-in types are immutable, which means that you cannot change the value of an object after an object is created. If you need a new value, you must create a new object. The immutable nature of the Python simple data type differs from the way most popular languages, such as the Java language, handle simple primitive types. However, when you have a better understanding of the object properties of these simple data types, it is easy to understand the difference.
So, how can integers have some method? Is it just a number? No, at least in Python the answer is no. You can test it yourself: with the built-in Help method, you can consult the Python interpreter for information about the Int object (see Listing 1).
Listing 1. Python interpreter: Help for Integer objects
rb% python python 2.4 (#1, Mar, 12:05:39) [GCC 3.3 20030304ppp (Apple Computer, in
C. Build 1495)] on Darwin Type ' help ', ' copyright ', ' credits ' or ' license ' for the more information. >>> Help (int) Help on class int in module __builtin__: Class int (object) |
Int (x[, base])-> integer | | Convert a string or number to an integer, if possible. A Floating Point | Argument'll be truncated towards zero (this does not include a string | Representation of a floating point number!) When converting a string, use | The optional base. It is the error to supply a base when converting a | Non-string. If The argument is outside the integer range a long object |
would be returned instead.
| |
Methods defined here: | |
__abs__ (...) |
x.__abs__ () <==> abs (x) | |
__add__ (...) |
x.__add__ (y) <==> x+y ...
What does this specifically mean? There is only one thing, which is that you can easily get help from the Python interpreter, but you can get more help from the latter part. The first line tells you that you are viewing the help page for the Int class, which is a built-in data type. If you are unfamiliar with the concept of object-oriented programming, you can imagine a class as just a blueprint for building special things and interacting with them. Like the blueprints for a house, it shows not just how to build a house, but how to use it better after the house is finished. For example, the plan shows the location of different rooms, the way they move between rooms, and the access to the house.
The first line below is a detailed description of the actual int class. At this point, you may not be familiar with how to create a class in Python because the syntax displayed is similar to a foreign language. Never mind, I'll make a comprehensive introduction to this in another article. Now all you need to know is that the Int object is inherited from the object class, which is a base class for many of the content in Python.
The following lines describe the constructor for the Int class. A constructor is simply a special way to create a particular class instance (or object). The constructor method is analogous to a construction contractor, which uses the design of a house to build a house. In Python, the name of a constructor is the same as the name of the class it creates. Classes can have different constructor methods, which are distinguished by the different attributes that come with the parentheses that come with the class name. A good example of a class that can have different constructor methods is the int class, in fact, you can invoke it in several ways, depending on the parameters placed in the parentheses (see Listing 2).
Listing 2. Python Interpreter: Int class constructor
>>> Int ()
0
>>> Int (m) # Create An integer with the value of
>>> int ("10 0 "," # Create an integer with the value of ' in base
' >>> int ("M", 8) # Crea Te an integer with the value of 8
64
These four constructor calls create four different integers. The first constructor creates an integer object with a value of 0, which is the default value that is used when no value is supplied to the Int class constructor. The second constructor creates an integer with a value of 100 according to the rule. The third constructor takes the string "100" and creates an integer value with a base of 10 (a common decimal system). The last constructor also takes the string "100"--but it uses cardinality 8来 to create an integer value, usually called octal. However, the value is converted to a decimal value when it is output, which is why the number appears to be 64.
You might want to know what happens if you omit the parentheses in the constructor call. In this case, you can assign an actual class name to the variable, effectively creating an alias for the original class (see Listing 3).
Listing 3. Python Interpreter: int type
>>> it = int # Create An alias to the integer class
>>> it (m)
>>> type (it # We created a new type
<type ' type ' >
>>> type (IT) # our new type just makes integer s
<type ' int ' >
Oh, that's great! You can immediately create a new data type that is defined by the built-in int class. But pay attention to the bad side and don't abuse this new feature. Excellent programmers should try to make the code clear in addition to the good performance of the code. Such coding techniques do have their value, but they are not common.
Using the Python interpreter allows the new Python programmer to simplify the learning process and reduce the detours. If you want to learn more about the Help tool within Python, you can access the Interactive helper tool (see Listing 4) simply by typing Assist () at a command prompt in the Python interpreter.
Listing 4. Python Interpreter: Help interpreter
>>> Help ()
Welcome to Python 2.4! This are the online Help utility.
The If is your the should definitely check out the tutorial on the
Internet at http://www.py thon.org/doc/tut/.
Enter the name of any module, keyword, or topic to get help on writing
python programs and using Python modules. To quit this help utility
and the interpreter, just type "quit".
To get a list of available modules, keywords, or topics, type "modules",
"keywords", or "topics". Each module, also comes with a one-line summary of
What it does, to list the modules whose, summaries contain a given Wo Rd
such as "spam", type "modules spam".
Help>
You may already know this, but entering int at the help> prompt can display the class descriptions that are displayed for the previous int class.
Container type
So far, the simple types used in many Python languages have been discussed. But most programs are not simple, they involve complex data that is usually composed of simple types. So the question now is, "How do you handle complex data in Python?" ”
If you are familiar with object-oriented languages, such as Java or C #, you might think the answer to the question is simple: simply create a new class to handle the complex data. This method also applies to Python, because Python supports creating new types from classes. However, in most cases, Python can also provide a simpler approach. When your program needs to work with multiple objects at once, you can take advantage of the Python container class:
Tuple
String
Unicode
List
Set
Frozenset
Dictionary
These types of containers provide two functions. The first six types are ordered, and the last type dictionary is a mapping. The difference between an ordered type and a mapping type is simpler. An ordered type simply refers to the order of objects. All ordered types (except set and Frozenset types) support access to objects of the given order. In contrast, the mapping container is used to hold objects that are not very sensitive to the order, and you can extract values in the cooler by providing a key that can find the value of the relationship.
Another difference between container types comes from the attributes of the data they hold, and the order of the following four container types is immutable:
Tuple
String
Unicode
Frozenset
This means that when you create one of these container types, the data you store is not changed. If you need to change the data for some reason, you need to create a new container to hold the new data.
The three container types (list, set, and dictionary) are variable containers, so they can change any data saved as needed (but the keys used in dictionary are immutable, like the keys to your room). Although variable containers are flexible, their dynamic characteristics can have an impact on performance. For example, the tuple type, although it is immutable and less flexible, is usually much faster than the list type when used in the same environment.
These container classes provide powerful features that are often at the heart of most Python programs. The remainder of this article discusses the tuple type, which is used to introduce a number of basic concepts related to creating and using container types in Python. The remaining types will be discussed in future articles.
META Group
The tuple type is like a pocket, where you can put whatever you need in front of your head. You can put your key, driver's license, pad and pen in your pocket, which is a collection box for all kinds of things. Python's tuple type is similar to a pocket, and it can hold different types of objects. You can create a tuple (see listing 5) by simply assigning a comma-delimited sequence of objects to the variable.
Listing 5. Python interpreter: Create a tuple
>>> t = (0,1,2,3,4,5,6,7,8,9)
>>> type (t)
<type ' tuple ' >
>>> t
(0, 1 , 2, 3, 4, 5, 6, 7, 8, 9)
>>> tt = 0,1,2,3,4,5,6,7,8,9
>>> type (TT)
<type ' tuple ' >
>>> tt
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> tc=tuple ((0,1,2,3,4,5,6,7,8,9))
>>> TC
(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> et = () # an empty tuple
>>> et
()
;>> st = (1,) # A Single Item tuple
>>> St
(1,)
The sample code shows how to create a tuple in a variety of ways. The first method is to create a tuple that contains a sequence of integers from 0 to 9. The second method is the same as the first, but this time the parentheses are omitted. When creating a tuple, parentheses are usually optional, but are sometimes required, depending on the context. As a result, you will habitually use parentheses to reduce confusion. The last tupletc uses an actual class constructor to create the tuple. The important point here is that there is only one variable in the constructor composition, so you must include the object sequence in parentheses. The last two constructor calls demonstrate how to create an empty tuple (ET) by not putting anything in parentheses, and how to create tuple (ST) by placing a comma behind the only item in the sequence.
One of the main reasons for using the pouch is to facilitate life. But ask to be able to remove them quickly from your pockets when you need them. Most container types in Python, including tuple, allow you to easily access data items from the collection using the square bracket operator. But Python is more flexible than other languages: You can select a project or multiple sequential items by using a method that is often called a fragment (see Listing 6).
Listing 6. Python interpreter: Accessing items from tuple
>>> t = (0,1,2,3,4,5,6,7,8,9)
>>> t[2]
2
>>> type (t[2])
<type ' int ' >
>>> t[0], t[1], t[9]
(0, 1, 9)
>>> T[2:7] # Slice out five elements from the tuple< c9/> (2, 3, 4, 5, 6)
>>> type (T[2:7])
<type ' tuple ' >
>>> t[2:7:2] # Slice Out three elements from the tuple
(2, 4, 6)
After creating a simple tuple, the previous example shows how to select a data item--In this case, Integer 2. At this point, note that Python uses 0 sorting, where items in the collection are numbered from zero. If you are familiar with programming using the Java language, C #, or other languages derived from C, you should be familiar with this behavior. Otherwise, the concept is very simple. The index used to access the data item declares only how far away from the first item of data in the collection is, or is called a sequence, and you need to get what you want. Therefore, to get the third data item (in this example, Integer 2), you need to cross two items from the first data item. When you access the third data item, Python knows that it is an integer object. You can also easily extract multiple data items from the collection. In this example, you create a new tuple value that starts with the first, second, and tenth values from the initial tuple.
The remaining examples show how to use the fragmentation feature of Python to select multiple items of data at once from a sequence. Term segmentation refers to the method of segmenting data items from a sequence. A fragment works by declaring a start index, an end index, and an optional step size, all separated by semicolons. Therefore, T[2:7] fragments the third to seventh data item in the tuple, and t[2:7:2] segments each of the two data items, starting with the third data item in the tuple to the seventh data item.
The tuple objects I am currently creating are homogeneous, and they contain only integer objects. Fortunately, tuple is much more complicated than the example shown, because tuple is actually a heterogeneous container (see listing 7).
Listing 7. Python Interpreter: Heterogeneous tuple
>>> t = (0,1, "two", 3.0, "Four", (5, 6))
>>> T
(0, 1, ' two ', 3.0, ' Four ', (5, 6))
>>> ; T[1:4]
(1, ' two ', 3.0)
>>> type (t[2))
<type ' str ' >
>>> type (t[3))
< Type ' float ' >
>>> type (t[5])
<type ' tuple ' >
>>> t[5] = (0,1)
Traceback (most recent call last):
File "<stdin>", line 1, in?
Typeerror:object does not support item assignment
You'll see how convenient it is to create a tuple that can have various types of data items, including another tuple. And you can access all data items in the same way using the square brackets operator, which supports segmenting different types of ordered data items. However, tuple is immutable. Therefore, when I try to change the Fifth element, I find that the assignment of the data item is not allowed. In a simple analogy, after you put something in your pocket, the only way to change what you take is to take a new pocket and put all the data items in it.
If you need to create a new tuple in an existing tuple that contains a subset of the data items, the easiest way is to use the associated fragment and add a subset as needed (see Listing 8).
Listing 8. Python Interpreter: Using tuple
>>> tn = T[1:3] + t[3:6] # Add Two tuples
>>> tn
(1, ' two ', 3.0, ' Four ', (5, 6))
>>> ; TN = T[1:3] + t[3:6] + (7,8,9, "ten")
>>> tn
(1, ' two ', 3.0, ' Four ', (5, 6), 7, 8, 9, ' ten ')
>>& Gt T2 = tn[:] # Duplicate A entire tuple, a full slice
>>> T2
(1, ' two ', 3.0, ' Four ', (5, 6), 7, 8, 9, ' Ten ')
>>> Len (TN) # Find out how many items are in the tuple
9
>>> tn[4][0] # Access a nested tuple
5
You can also combine fragments of an existing tuple with fragments of a new tuple. With fragment syntax, you can make a copy of an existing tuple without specifying a start or end index. The last two examples are also very interesting. The built-in Len method tells you the number of data items in the tuple. Accessing data items from nested tuple is also very simple: Select the nested tuple and access the interesting data items from it.
You can also create a tuple from a set of existing variables called the packaging process. And vice versa, where the value in tuple is assigned to the variable. The following process is called unpack, which is a very powerful technique for many scenarios, including the desire to return multiple values from a function. When you unpack tuple, the only problem is that you must supply a variable for each data item in tuple (see Listing 9).
Listing 9. Python interpreter: Packing and wrapping tuple
>>> i = 1
>>> s = "two"
>>> f = 3.0
>>> t = (I, S, f) # Pack The Varia Bles into a tuple
>>> t
(1, ' two ', 3.0)
>>> II, SS, FF = T # Unpack the tuple into the n Amed variables
>>> II
1
>>> II, FF = t # enough variables to unpack three element Tuple
Traceback (most recent call last):
File "<stdin>", line 1, in?
Valueerror:too Many values to unpack
Simplifying Concepts
Although it may seem complex, the object properties of Python actually simplify some of the more complex concepts that are often faced by novice python languages. After learning how to use objects, everything is an object. This concept means that you have further understood some of the new concepts. such as the Python container type. Simplifying a difficult task is one of the common benefits of using Python; another example is the built-in Help tool, which you can see in the Python interpreter by simply typing in the aid () at the Python prompt. Since life is not described with some simple concepts, Python provides a rich set of container (i.e., collection) objects. In this article, I introduced one of the simplest object--tuple. To use tuple correctly, you need to be familiar with how it works. However, because many other container types have similar functionality, including fragmentation and packaging or unpack, understanding how tuple works means that you are beginning to fully understand the other container types in Python.