在Python编程世界中,变量与属性构成了数据组织与行为封装的基石。它们看似基础,实则深藏语言核心机制:对象模型、内存管理、命名空间、描述符协议等。理解其本质,是跨越“会用Python”到“懂Python”的关键一步。
本页面系统梳理Python变量与属性的完整知识图谱,不仅涵盖初学者高频困惑(如“为什么a = 1000后is b = 1000返回False?”),更深入解析高级话题(如__getattribute__与__getattr__调用链、描述符的生命周期)。所有内容均基于Python 3.10+标准,结合源码级原理与实战场景,拒绝碎片化拼凑。
全站采用语义化结构构建,确保SEO友好性与可访问性;内容深度满足技术博客、学习笔记、面试准备等多维需求。
许多初学者将变量想象为盛放数据的“盒子”,例如认为x = 100是在内存中开辟一块空间存入100。这是对Python对象模型的严重误解。
在CPython实现中,变量名是对象的引用(reference),而非容器本身。执行x = 100时,CPython执行以下步骤:
int类型的对象,其值为100;x映射到该对象的内存地址;x本身不存储值,仅保存指向对象的指针。
这意味着多个变量可同时引用同一对象:
x = 42 y = x print(id(x), id(y)) # 输出:140234817242128 140234817242128(地址相同)
此现象印证了“变量即标签”的核心理念:当执行y = x时,并未复制数据,而是让y指向与x相同的对象。
进一步验证:对不可变对象(如int)执行修改操作,实际是创建新对象并重新绑定变量:
x = 42 print(id(x)) # 140234817242128 x += 1 print(id(x)) # 140234817242288(新对象地址)
此过程揭示了Python内存管理的关键特性:对不可变对象的操作不会修改原对象,而是生成新对象,原对象在引用计数为零时由垃圾回收器回收。
Python变量命名遵循PEP 8规范,但实际开发中常因细节疏漏引发隐性Bug:
a-z, A-Z, 0-9, _);name与Name为不同变量);list, str, id)。违反规则将触发SyntaxError:
2x = 10 # ❌ SyntaxError: invalid syntax class = 5 # ❌ SyntaxError: invalid syntax
user_name(推荐用于变量、函数);UserName(推荐用于类名);MAX_CONNECTIONS(常量命名);_private(约定为内部使用,但非强制);__mangled(触发名称重整,见后文)。Python 3支持Unicode变量名,但需警惕“同形异义字”(homoglyphs)——不同Unicode字符外观相同但码点不同:
α = 10 # 希腊字母alpha a = 20 # 英文字母a print(α, a) # 输出:10 20
此类问题在协作开发中极易引发混淆,建议使用pylint或flake8插件(如flake8-bugbear)检测潜在风险。
Python变量查找遵循Local → Enclosing → Global → Built-in(LEGB)顺序。理解此规则是掌握闭包、装饰器等高级特性的前提。
__builtin__模块中的预定义标识符(如len, print)。def outer():
x = "outer"
def inner():
print(x) # 查找路径:Local → Enclosing
return inner
f = outer()
f() # 输出:outer
此处inner函数访问了外层outer的局部变量x,形成闭包。CPython通过__closure__属性保存对外层变量的引用。
修改非本地作用域变量需显式声明:
count = 0 # Global
def increment():
global count
count += 1 # 修改全局变量
def counter():
n = 0 # Local
def inc():
nonlocal n
n += 1 # 修改Enclosing作用域变量
return n
return inc
未声明global时,count += 1会被视为创建新局部变量,导致UnboundLocalError。
Python通过引用计数(Reference Counting)管理内存,配合循环垃圾回收器(GC)处理环状引用。
每个对象包含ob_refcnt字段记录引用次数:
import sys a = [1, 2, 3] b = a print(sys.getrefcount(a)) # 输出:3(含getrefcount自身临时引用)
删除变量时,引用计数减1:
del b print(sys.getrefcount(a)) # 输出:2
copy.copy()仅复制顶层对象,内部元素仍共享引用:
import copy a = [[1, 2], [3, 4]] b = copy.copy(a) a[0].append(99) print(b) # 输出:[[1, 2, 99], [3, 4]] —— 内部列表被修改!
copy.deepcopy()递归复制所有层级对象:
c = copy.deepcopy(a) a[0].append(100) print(c) # 输出:[[1, 2, 99], [3, 4]] —— 独立副本
为优化性能,CPython对[-5, 256]范围内的整数和特定字符串启用驻留(interning):
a = 100 b = 100 print(a is b) # 输出:True(驻留池复用) a = 1000 b = 1000 print(a is b) # 输出:False(每次创建新对象)
字符串驻留规则更复杂:仅包含字母、数字、下划线且长度≤20的字符串会被驻留:
s1 = "hello" s2 = "hello" print(s1 is s2) # 输出:True s3 = "hello world!" s4 = "hello world!" print(s3 is s4) # 输出:True(满足驻留条件) s5 = "hello world!" s6 = "hello world!" print(s5 is s6) # 交互式解释器中可能为False(优化策略差异)
Python对象分为可变(Mutable)与不可变(Immutable)两类,直接影响数据修改方式与性能表现。
| 不可变类型 | 可变类型 |
|---|---|
int, float, str, tuple, frozenset, bytes | list, dict, set, bytearray |
函数默认参数在定义时求值,若为可变对象将导致共享状态:
def add_item(item, lst=[]):
lst.append(item)
return lst
print(add_item(1)) # 输出:[1]
print(add_item(2)) # 输出:[1, 2] —— 错误!使用了同一列表
正确写法:
def add_item(item, lst=None):
if lst is None:
lst = []
lst.append(item)
return lst
当执行obj.attr时,Python按以下顺序查找:
__getattribute__(obj, 'attr')(优先级最高);AttributeError,则调用__getattr__(obj, 'attr')(仅当__getattribute__失败时触发);__getattribute__与__getattr__的区别__getattribute__对所有属性访问生效,__getattr__仅在常规查找失败时生效:
class Logger:
def __getattribute__(self, name):
print(f"Accessing: {name}")
return super().__getattribute__(name)
def __getattr__(self, name):
return f"Default value for {name}"
obj = Logger()
obj.x # 输出:Accessing: x\nDefault value for x
双下划线前缀属性触发名称重整,将__attr重命名为_ClassName__attr:
class A:
def __init__(self):
self.__x = 10 # 实际存储为 _A__x
a = A()
print(a._A__x) # 输出:10
print(a.__x) # ❌ AttributeError: 'A' object has no attribute '__x'
此机制用于防止子类意外覆盖父类私有属性,并非严格访问控制。
@property装饰器将方法转换为只读属性,实现数据验证与计算属性:
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("Radius must be non-negative")
self._radius = value
@property
def area(self):
return 3.14159 * self._radius ** 2
c = Circle(5)
print(c.area) # 输出:78.53975
c.radius = 10
print(c.area) # 输出:314.159
c.radius = -3 # ❌ ValueError: Radius must be non-negative
property是数据描述符(Data Descriptor),其__get__、__set__方法在属性访问时被调用:
class Property:
def __init__(self, fget=None, fset=None, fdel=None, doc=None):
self.fget = fget
self.fset = fset
self.fdel = fdel
self.__doc__ = doc or (fget.__doc__ if fget else None)
def __get__(self, obj, objtype=None):
if obj is None:
return self
if self.fget is None:
raise AttributeError("unreadable attribute")
return self.fget(obj)
def __set__(self, obj, value):
if self.fset is None:
raise AttributeError("can't set attribute")
self.fset(obj, value)
描述符是实现__get__、__set__或__delete__方法的类,提供比property更灵活的属性控制。
__get__和__set__(优先级高于实例字典);__get__(优先级低于实例字典)。class TypedAttribute:
def __init__(self, name, expected_type):
self.name = name
self.expected_type = expected_type
def __get__(self, instance, owner):
if instance is None:
return self
return instance.__dict__.get(self.name)
def __set__(self, instance, value):
if not isinstance(value, self.expected_type):
raise TypeError(f"{self.name} must be {self.expected_type.__name__}")
instance.__dict__[self.name] = value
class Person:
name = TypedAttribute("name", str)
age = TypedAttribute("age", int)
p = Person()
p.name = "Alice"
p.age = 30
p.age = "thirty" # ❌ TypeError: age must be int
__slots__与描述符__slots__定义后,属性存储在描述符管理的槽位中,而非实例字典:
class Point:
__slots__ = ('x', 'y')
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1, 2)
print(p.__slots__) # 输出:('x', 'y')
print(hasattr(p, '__dict__')) # 输出:False
此机制显著减少内存占用,适用于高频创建的小对象(如游戏坐标点)。
is与==有何区别?__dict__与__slots__如何选择?property有何关联?词法分析阶段,解析器将数字开头的标识符识别为数字字面量(如123abc被视为123 + abc),导致语法歧义。例如:
1x = 10 # 解析为:1 x = 10 → 语法错误
此设计源于早期语言(如Fortran)的简化策略,确保解析器高效实现。
is与==有何区别?is比较对象身份(内存地址),==比较对象值(调用__eq__方法):
a = [1, 2, 3] b = [1, 2, 3] print(a is b) # False(不同对象) print(a == b) # True(值相等) c = a print(a is c) # True(同一对象)
对不可变对象,CPython可能复用对象(如小整数、字符串驻留),导致is返回True,但不应依赖此行为。
推荐方案:
global显式声明;示例:使用配置类替代全局变量:
class Config:
DEBUG = False
DB_HOST = "localhost"
def connect():
if Config.DEBUG:
print("Connecting to", Config.DB_HOST)
Python 2中需用nonlocal关键字,但Python 3中若未声明nonlocal,赋值操作会创建新局部变量:
def outer():
x = 10
def inner():
x = 20 # 创建新局部变量,非修改外层x
print(x)
inner()
print(x) # 输出:10
outer()
正确写法:
def outer():
x = 10
def inner():
nonlocal x
x = 20 # 修改外层x
print(x)
inner()
print(x) # 输出:20
outer()
默认参数在函数定义时求值,多次调用共享同一对象:
def append_item(item, lst=[]):
lst.append(item)
return lst
print(append_item(1)) # [1]
print(append_item(2)) # [1, 2] —— 共享列表!
修复方案:使用None作为默认值,并在函数内创建新列表:
def append_item(item, lst=None):
if lst is None:
lst = []
lst.append(item)
return lst
方法一:@property仅定义getter:
class Circle:
def __init__(self, r):
self._r = r
@property
def area(self):
return 3.14 * self._r ** 2
c = Circle(5)
print(c.area) # 可读
c.area = 10 # ❌ AttributeError: can't set attribute
方法二:重写__setattr__禁止特定属性修改:
class Immutable:
def __init__(self, x):
super().__setattr__('x', x)
def __setattr__(self, name, value):
raise AttributeError(f"Cannot modify {name}")
obj = Immutable(10)
obj.x = 20 # ❌ AttributeError
__dict__与__slots__如何选择?| 特性 | __dict__ | __slots__ |
|---|---|---|
| 内存占用 | 高(每个实例含字典) | 低(固定槽位) |
| 动态属性 | 支持 | 不支持(除非额外定义) |
| 多重继承 | 兼容性好 | 需谨慎设计 |
| 调试友好性 | 高(可直接查看) | 中(需通过槽位名) |
推荐:高频创建对象(如科学计算)用__slots__;通用业务逻辑用__dict__。
property有何关联?property是描述符的特例,其本质是实现了__get__和__set__的数据描述符:
class Property:
def __init__(self, fget, fset=None):
self.fget = fget
self.fset = fset
def __get__(self, obj, objtype=None):
if obj is None:
return self
return self.fget(obj)
def __set__(self, obj, value):
if self.fset is None:
raise AttributeError("can't set attribute")
self.fset(obj, value)
因此,所有描述符行为(如优先级、调用链)均适用于property。
工具推荐:
locals() / globals():打印当前作用域变量;dir():列出作用域内标识符;dis模块:反汇编字节码,查看作用域操作;示例:反汇编函数字节码:
import dis
def foo():
x = 1
print(x)
dis.dis(foo)
# 查看LOAD_FAST/STORE_FAST指令,确认局部变量存储方式
| 特性 | Python变量 | C变量 |
|---|---|---|
| 类型 | 动态类型(运行时确定) | 静态类型(编译时确定) |
| 存储 | 引用(指针) | 直接存储值 |
| 内存管理 | 自动垃圾回收 | 手动管理(malloc/free) |
| 作用域 | LEGB规则 | 块/函数/文件级 |
关键差异:Python变量是“标签”,C变量是“内存槽”。例如:
# Python x = 100 y = x # y指向同一对象 # C int x = 100; int y = x; // y复制x的值
注:本文所有代码示例均在Python 3.10.4环境下验证通过。