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

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.

主站蜘蛛池模板: 马关县| 徐水县| 栖霞市| 祁连县| 缙云县| 民勤县| 奎屯市| 洮南市| 长治市| 河北区| 镶黄旗| 永新县| 洪江市| 定陶县| 全南县| 清水河县| 乐陵市| 将乐县| 阿巴嘎旗| 承德市| 吴旗县| 济南市| 塘沽区| 什邡市| 原平市| 梁河县| 南城县| 米林县| 阿勒泰市| 汾西县| 瑞丽市| 江阴市| 荔浦县| 保亭| 自贡市| 多伦县| 新乡市| 永胜县| 高淳县| 莆田市| 东安县|