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

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.

主站蜘蛛池模板: 彭水| 时尚| 黔西| 正蓝旗| 维西| 玉环县| 太仆寺旗| 静海县| 大姚县| 遂平县| 临漳县| 延津县| 罗定市| 襄垣县| 五寨县| 敦化市| 重庆市| 遂宁市| 吴桥县| 宁海县| 荆州市| 江油市| 鞍山市| 平和县| 泰安市| 石泉县| 神木县| 左云县| 温泉县| 于田县| 彭泽县| 驻马店市| 鄢陵县| 二连浩特市| 宣恩县| 利川市| 曲阳县| 五寨县| 白朗县| 盐亭县| 苏尼特右旗|