Python中如何在类方法中获取类实例的变量名?
获取Python类实例的变量名
首先得明确:Python的实例本身不会记录自己被哪个变量引用——因为一个实例可以被多个变量指向(比如pet2 = pet1),所以没有内置的直接方法获取变量名。不过有两种可行的解决思路:
方法1:创建实例时手动传入变量名
这是最可靠的方式,在初始化实例时把变量名作为参数传入并保存,之后直接在方法中使用:
class Pet(): def __init__(self, name, species, var_name): self.name = name self.species = species self.var_name = var_name # 保存变量名 def petVar(self): print(f"{self.var_name} is the name of the variable") pet1 = Pet("peter", "cat", "pet1") pet1.petVar() # 输出:pet1 is the name of the variable
方法2:遍历作用域查找实例对应的变量名
通过遍历当前作用域的变量,找到指向该实例的变量名,但这种方法有局限性:
class Pet(): def __init__(self, name, species): self.name = name self.species = species def petVar(self): # 遍历全局作用域的变量,匹配当前实例 for var_name, obj in globals().items(): if obj is self: print(f"{var_name} is the name of the variable") return print("未找到对应的变量名") pet1 = Pet("peter", "cat") pet1.petVar() # 输出:pet1 is the name of the variable
注意:
- 如果实例是在函数内部创建的,需要用
locals()代替globals() - 如果多个变量指向同一个实例,只会打印第一个匹配到的变量名
- 若实例的引用被删除(比如
del pet1),则无法找到变量名
内容的提问来源于stack exchange,提问作者CuriousCoder
相关产品推荐
相关产品推荐

