Detailed explanation of Python data types (variable and immutable types)

1 Overview

Insert picture description here

2 6 standard data types

Insert picture description here

2.1 Immutable data: number, string, tuple

  • Elements in this type 不能被修改 -> 若强行赋值,则报错
var_number = 123
var_string = "abc"
var_tuple = (1, 2, 3)

print(id(var_number))
print(id(var_string))
print(id(var_tuple))

# var_string[0] = 'A'  # 报错,字符串中的元素不能被修改
# var_tuple[0] = (11)  # 报错,元祖中的元素不能被修改

2.2 Variable data: list, set, dictionary

  • Elements in this type 可以被修改 -> id() 不变
var_list = [1, 2, 3]
var_set = {
    
    'a', 'b', 'c'}
var_dictionary = {
    
    'name': 'YoYo', 'age': 18}

print(id(var_list))
print(id(var_set))
print(id(var_dictionary))

var_list[0] = '111'
var_set.add('d')
var_dictionary.pop('age')

print('------- 万恶的分割线 -------')
print(id(var_list))
print(id(var_set))
print(id(var_dictionary))

print(var_list)  # ['111', 2, 3]
print(var_set)  # {'d', 'b', 'c', 'a'}
print(var_dictionary)  # {'name': 'YoYo'}

3 Data type judgment

3.1 The difference between type and isinstance

Similarity: Under normal circumstances, it can be used to determine the type of variable

a = 1

print(type(a))  # int
print(isinstance(a, int))  # True

difference:

1. type() 不会认为 '子类' 是一种 '父类' 类型
2. isinstance() 会认为 '子类' 是一种 '父类' 类型
class Father:
    pass


class Son(Father):
    pass


print(isinstance(Father(), Father))  # True
print(isinstance(Son(), Father))  # True

print(type(Father()) == Father)  # True
print(type(Son()) == Father)  # False

Guess you like

Origin blog.csdn.net/qq_34745941/article/details/108485076