官术网_书友最值得收藏!

Overview of data types and objects

Python contains 12 built-in data types. These include four numeric types (int, float, complex, bool), four sequence types (str, list, tuple, range), one mapping type (dict), and two set types. It is also possible to create user-defined objects such as functions or classes. We will look at the string and the list data types in this chapter and the remaining built-in types in the next chapter.

All data types in Python are objects. In fact, pretty much everything is an object in Python, including modules, classes, and functions, as well as literals such as strings and integers. Each object in Python has a type, a value, and an identity. When we write greet = "hello world" we are creating an instance of a string object with the value "hello world" and the identity of greet. The identity of an object acts as a pointer to the object's location in memory. The type of an object, also known as the object's class, describes the object's internal representation as well as the methods and operations it supports. Once an instance of an object is created, its identity and type cannot be changed.

We can get the identity of an object by using the built-in function id(). This returns an identifying integer and on most systems this refers to its memory location, although you should not rely on this in any of your code.

Also, there are a number of ways to compare objects, for example:

    if a== b: #a and b have the same value 

if a is b: # if a and b are the same object
if type(a) is type(b): # a and b are the same type

An important distinction needs to be made between mutable and immutable objects. Mutable object's such as lists can have their values changed. They have methods, such as insert() or append(), that change an objects value. Immutable objects, such as strings, cannot have their values changed, so when we run their methods, they simply return a value rather than change the value of an underlying object. We can, of course, use this value by assigning it to a variable or using it as an argument in a function.

主站蜘蛛池模板: 延长县| 勃利县| 玉门市| 濉溪县| 兰溪市| 灵璧县| 米林县| 沙雅县| 孝昌县| 沂南县| 黔西| 远安县| 静海县| 耒阳市| 中阳县| 江津市| 老河口市| 包头市| 临漳县| 叙永县| 永宁县| 竹山县| 陆河县| 久治县| 信阳市| 邛崃市| 康平县| 咸宁市| 兴山县| 宁远县| 洛扎县| 武威市| 永德县| 南木林县| 巴里| 昌图县| 江源县| 中方县| 循化| 宁德市| 厦门市|