Python变量声明与赋值
Python 变量是对象的引用,无需声明类型,赋值即创建变量。
变量赋值机制
基本赋值
Python
x = 10 # 创建整数对象 10,变量 x 引用它
name = "Alice" # 创建字符串对象,name 引用它
is_active = True # 布尔值
print(x) # 10
print(name) # Alice
变量是引用,不是存储值
Python
a = [1, 2, 3]
b = a # b 引用同一列表对象
b.append(4)
print(a) # [1, 2, 3, 4](a 也被修改)
print(b) # [1, 2, 3, 4]
# a 和 b 指向同一对象
print(a is b) # True
重新赋值
Python
x = 10
x = "hello" # x 引用新对象,类型可变
print(x) # hello
print(type(x)) # str
动态类型特性
类型可随时改变
Python
value = 10
print(type(value)) # int
value = 3.14
print(type(value)) # float
value = "hello"
print(type(value)) # str
类型检查
Python
x = 10
if isinstance(x, int):
print("x is integer")
# 查看类型
print(type(x).__name__) # int
Python 不需要预先声明变量类型,运行时确定。
内存引用
id() 查看对象地址
Python
a = 10
b = 10
print(id(a)) # 对象内存地址
print(id(b)) # 相同地址(小整数缓存)
print(a is b) # True
a = 1000
b = 1000
print(a is b) # 可能 False(大整数不缓存)
小整数缓存
Python
# Python 缓存 -5 到 256 的整数
for i in range(-5, 256):
a = i
b = i
print(i, a is b) # 均为 True
字符串缓存
Python
# 短字符串和标识符形式字符串可能缓存
s1 = "hello"
s2 = "hello"
print(s1 is s2) # True(常被缓存)
s1 = "hello world!"
s2 = "hello world!"
print(s1 is s2) # 可能 False
多重赋值
链式赋值
Python
a = b = c = 10
print(a, b, c) # 10 10 10
print(a is b is c) # True(引用同一对象)
元组解包赋值
Python
a, b, c = 1, 2, 3
print(a, b, c) # 1 2 3
# 交换变量
x, y = 10, 20
x, y = y, x
print(x, y) # 20 10
列表解包
Python
values = [1, 2, 3]
a, b, c = values
print(a, b, c) # 1 2 3
扩展解包
Python
first, *middle, last = [1, 2, 3, 4, 5]
print(first) # 1
print(middle) # [2, 3, 4]
print(last) # 5
*rest, last = [1, 2, 3]
print(rest) # [1, 2]
print(last) # 3
变量命名规则
合法命名
Python
# 合法变量名
name = "Alice"
_age = 25
count_1 = 100
MAX_VALUE = 999
非法命名
Python
# 非法(会报错)
# 1name = "Alice" # 不能数字开头
# my-var = 10 # 不能包含 -
# class = "math" # 不能用关键字
命名约定
Python
# 小写 + 下划线(推荐)
user_name = "Alice"
total_count = 100
# 类名:大驼峰
class MyClass:
pass
# 常量:全大写
MAX_CONNECTIONS = 100
# 私有变量:前缀下划线
_internal_value = 10
要点总结
- Python 变量是对象引用,赋值即创建
- 无需声明类型,动态确定
- 变量可随时引用不同类型对象
id()查看对象地址,is判断同一对象- 使用多重赋值、解包提高效率
📝 发现内容有误?点击此处直接编辑