在 Python 中,__dict__ 属性用于存储对象的可写属性,但并非所有对象都有这个属性
没有 __dict__ 属性的对象类型及其特征:
1. 内置数据类型实例
基本数据类型
整数 (int): 1, 42, -5
浮点数 (float): 3.14, 2.0, -0.5
复数 (complex): 1+2j, 3-4j
布尔值 (bool): True, False
字符串 (str): "hello", 'world'
字节 (bytes): b"data", b'\x00\x01'
容器类型
列表 (list): [1, 2, 3]
元组 (tuple): (1, 2, 3)
字典 (dict): {"a": 1, "b": 2}
集合 (set): {1, 2, 3}
冻结集合 (frozenset): frozenset([1, 2, 3])
2. 使用 __slots__ 的类实例 python class SlottedClass: __slots__ = ['x', 'y'] # 限制只能有这些属性 def __init__(self, x, y): self.x = x self.y = y obj = SlottedClass(1, 2) print(hasattr(obj, '__dict__')) # 输出: False
3. 某些内置对象和单例
None: None
Ellipsis: ...
NotImplemented: NotImplemented
内置函数和内置方法: len, print, [].append
4. 使用 C 扩展实现的对象
NumPy 数组: numpy.array([1, 2, 3])
Pandas DataFrame: pandas.DataFrame(...)
许多科学计算和数据处理库的对象
5. 模块对象 python import math print(hasattr(math, '__dict__')) # 输出: True - 模块实际上有 __dict__ # 但某些特殊模块可能没有完整的 __dict__ import sys print(hasattr(sys, '__dict__')) # 输出: True 6. 使用 __getattr__ 或 __getattribute__ 重写的对象 python class DictLess: def __getattr__(self, name): return f"Value for {name}" def __setattr__(self, name, value): # 不存储属性,只是打印 print(f"Would set {name} = {value}") obj = DictLess() print(hasattr(obj, '__dict__')) # 输出: False 7. 特殊类型的对象 枚举值 (enum.Enum): python from enum import Enum class Color(Enum): RED = 1 GREEN = 2 print(hasattr(Color.RED, '__dict__')) # 输出: False 内存视图 (memoryview): memoryview(b'abc') 范围对象 (range): range(10) 切片对象 (slice): slice(0, 10, 2) 8. 使用 ctypes 创建的对象 python import ctypes class Point(ctypes.Structure): _fields_ = [("x", ctypes.c_int), ("y", ctypes.c_int)] p = Point(1, 2) print(hasattr(p, '__dict__')) # 输出: False 9. 使用 __new__ 方法返回的非标准对象 python class Singleton: _instance = None def __new__(cls): if cls._instance is None: # 返回一个简单的对象,没有 __dict__ cls._instance = object.__new__(cls) return cls._instance obj = Singleton() print(hasattr(obj, '__dict__')) # 输出: True - 实际上 object.__new__ 创建的对象有 __dict__
Python 中没有 __dict__ 属性的对象主要包括:
基本内置数据类型(整数、字符串等)
使用 __slots__ 的类实例
某些特殊对象(None、Ellipsis 等)
使用 C 扩展实现的对象
枚举值和其它特殊类型的对象