如何获取在类的方法中定义的所有变量的名称 [英] How to get names of all the variables defined in methods of a class

查看:21
本文介绍了如何获取在类的方法中定义的所有变量的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

class Foo(object):
    def setUp(self):
        self.var1 = "some value"
        self.var2 = something
    def bar(self):
        var3 = some value
    def baz(self, var):
        var4 = some value

我想打印方法中定义的所有变量的名称,例如:

I want to print the names of all variables defined inside the methods, like:

setUp, bar, baz, var1, var2, var3, var4

我尝试过使用 locals(), vars(), globals() 但我只得到方法的名称,而不是变量名称.

I have tried using locals(), vars(), globals() but I am getting only the names of method and not variable names.

我也尝试过使用 ast 模块,但没有成功.

I also tried using ast module, but no success.

推荐答案

class Foo(object):
    def setUp(self):
        self.var1 = "some value"
        self.var2 = "something"
    def bar(self):
        var3 = "some value"
    def baz(self, var):
        var5 = 34


print Foo.setUp.__code__.co_varnames
print Foo.bar.__code__.co_varnames
print Foo.baz.__code__.co_varnames
Output:
('self',)
('self', 'var3')
('self', 'var', 'var5')




 #There are many more things in __code__ dict:
   # '__class__', '__cmp__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'co_argcount', 'co_cellvars', 'co_code', 'co_consts', 'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars', 'co_lnotab', 'co_name', 'co_names', 'co_nlocals', 'co_stacksize', 'co_varnames']

这篇关于如何获取在类的方法中定义的所有变量的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆