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

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.

主站蜘蛛池模板: 凤凰县| 工布江达县| 思茅市| 阿巴嘎旗| 西贡区| 江城| 泸定县| 黑水县| 永兴县| 林口县| 二手房| 彝良县| 色达县| 秦皇岛市| 台湾省| 招远市| 沂水县| 汉沽区| 常宁市| 武强县| 淅川县| 大冶市| 华亭县| 石家庄市| 江山市| 芒康县| 遂昌县| 海阳市| 广水市| 双桥区| 怀来县| 华池县| 新闻| 望江县| 宁海县| 永定县| 筠连县| 景洪市| 师宗县| 绥阳县| 小金县|