1. Python 变量和数据类型
Python-变量
-
变量不需要声明。变量也没有类型。使用前必须初始化(赋值操作)
-
变量在第一次赋值的时候被创建,创建之后的变量包含以下信息:
- 变量的标识(内存地址): The identifier used to reference the variable
- 变量的类型:这里所说的变量的类型,其实是指Value 的类型。The data type of the value.
- 变量的值: The data assigned to the variable.
Python 变量赋值的特殊写法(在一行代码中,同时赋值多个变量)
1 |
|
上述代码的输出:
a = 1, b = 1, c = 1
d = 1, e = 2, f = john
Python-标准数据类型
Python 中有六个标准数据类型:
-
不可变数据:Number, string, tuple
Number
有四种类型:int, float, complex, bool
; 这四种类型均继承自numbers.Number
-
可变数据: list, dict, set
可变类型和不可变类型的特点:
Immutable Data Types:
- Immutability: Cannot be changed after they are created.Any modification to an immutable obj results in the creation of a new obj.
- Hashable: Can be used as keys in dicts and elements in sets.
Mutable Date Types:
- Mutability: Can be changed after they are created.(add, remove, etc.)
- Not Hashable: Cannot be used as keys in dicts or elements in sets
“In Python, an object is considered hashable if it has a hash value that remains constant during its lifetime.”
Number
1 |
|
这里只介绍取商运算符和复数,其他略
将Number
中的一个特殊运算符操作//
(取商) 做如下展示:
1 |
|
上述代码输出:
c = 0.5, d = 0, e = 2
复数:通过j
作为数字的后缀,来创建。
1 |
|
str,tuple 和 list,dict,set的关系
String
, Tuple
, List
, Dictionary
, and Set
in Python share common characteristics because they all inherit from certain base classes that provide these functionalities. The common base classes include:
- Iterable: All these types inherit from the
Iterable
class, which allows them to be iterated over. - Container: They inherit from the
Container
class, which allows the use of thein
keyword to check for containment. - Sized: They inherit from the
Sized
class, which provides thelen()
function to get the number of elements.
Here is a brief overview of the inheritance hierarchy:
- String (
str
): Inherits fromSequence
, which in turn inherits fromIterable
,Container
, andSized
. - Tuple (
tuple
): Inherits fromSequence
, which in turn inherits fromIterable
,Container
, andSized
. - List (
list
): Inherits fromMutableSequence
, which in turn inherits fromSequence
,Iterable
,Container
, andSized
. - Dictionary (
dict
): Inherits fromMutableMapping
, which in turn inherits fromMapping
,Iterable
,Container
, andSized
. - Set (
set
): Inherits fromMutableSet
, which in turn inherits fromSet
,Iterable
,Container
, andSized
.
这也是为什么 len(),in,iterate 的操作可以在这几个数据类型上使用的原因。
用代码查看如下:
1 |
|
上述结果均输出:
True