You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从内存中读取Python类实例对应的变量名并输出?

实现方案

优先推荐:修改类结构(稳定可靠)

靠内存地址反查变量名的实现逻辑非常不稳定,存在大量边界问题:比如同一个对象可以绑定多个变量名、对象脱离作用域后没有绑定的变量名、局部作用域和全局作用域查询结果冲突等,生产环境更推荐直接在类定义中增加名称属性来实现需求。

修改后的模块代码

class Fridge:
    def __init__(self):
        self.isOpened = False
        self.foods = []

    def open(self):
        self.isOpened = True

    def put(self, thing):
        if self.isOpened:
            self.foods.append(thing)

    def close(self):
        self.isOpened = False

    # 新增获取食物名称列表的专用方法
    def list_food_names(self):
        return [food.name for food in self.foods]

class Food:
    def __init__(self, name):
        self.name = name
    # 重写实例打印规则,直接展示名称
    def __repr__(self):
        return f"'{self.name}'"

调用代码

import class_practice as fridge

f = fridge.Fridge()
apple = fridge.Food("apple")
elephant = fridge.Food("elephant")

f.open()
f.put(apple)
f.put(elephant)

print(f.foods)
# 输出:['apple', 'elephant']
print(f.list_food_names())
# 输出:['apple', 'elephant']

非常规方案:反查对象绑定的变量名(仅做实验用,不推荐生产使用)

你提到的ctypes方案无法满足需求:该方案是通过内存地址获取对应的对象本身,你之前的示例能拿到hello是因为你存的对象就是字符串本身,而你现在的Food实例没有存储名称属性,就算拿到对象也无法直接得到变量名。
如果一定要反查变量名,可以通过遍历调用栈的局部变量实现:

import class_practice as fridge
import inspect

def get_var_name_by_obj(obj):
    # 遍历当前调用栈的所有局部作用域
    for stack_frame in inspect.stack():
        for var_name, var_val in stack_frame.frame.f_locals.items():
            if var_val is obj:
                return var_name
    return repr(obj)

f = fridge.Fridge()
apple = fridge.Food()
elephant = fridge.Food()

f.open()
f.put(apple)
f.put(elephant)

res = [get_var_name_by_obj(food) for food in f.foods]
print(res)
# 输出:['apple', 'elephant']

内容的提问来源于stack exchange,提问作者code gen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 07:09:04