##language:zh #pragma section-numbers off ##含有章节索引导航的 ZPyUG 文章通用模板 <> ## 默许导航,请保留 <> = 如何返回实例名称 = ##startInc == 起问 == {{{ Yi Zhou zyd320@gmail.com 发件人当地时间: 发送时间 14:37 (GMT-07:00)。发送地当前时间:上午2:13。 ✆ 回复: python-cn@googlegroups.com 发送至: "python-cn(华蟒用户组,CPyUG 邮件列表)" 主题: [CPyUG] 如何返回实例名称? }}} 一个函数,有一个参数,现在需要返回这个参数的名字,怎么实现? 比如 {{{ #!python def function(arg): return arg.name asdfasdf={} function(asdfasdf) }}} 我现在想让函数返回 'asdfasdf‘ 这个字符串,怎么写这个函数? == Musheng == {{{ Musheng sheng.2179@gmail.com 发件人当地时间: 发送时间 20:57 (GMT+08:00)。发送地当前时间:下午5:17。 ✆ }}} {{{ #!python import inspect def call_me(who,what=''): f=inspect.currentframe() cd=f.f_code print cd.co_varnames[:cd.co_argcount] if __name__=='__main__': call_me('python') }}} == hongqn == {{{ Qiangning Hong hongqn@douban.com 通过“googlegroups.com” 发件人当地时间: 发送时间 18:11 (GMT+08:00)。发送地当前时间:下午5:16。 ✆ }}} === gc === 对象本身没有名字,只有名字绑定。一个对象可以绑定在多个名字上。 用 gc 模块可以得到对指定对象的所有引用,可以遍历这个引用找到可能的绑定在对象上的名字。 代码示例: {{{ #!python import gc def get_possible_names(obj): names = set() for ref in gc.get_referrers(obj): if type(ref) is dict: names.update(k for k, v in ref.iteritems() if v is obj) return names asdfasdf = {} print get_possible_names(asdfasdf) # 输出 set(['asdfasdf']) }}} 不过话说回来,这种做法很不可靠,而且这个需求本身也很没有意义。 === opcode === 楼主想要的是获取一个作为函数参数对象的名字。想到还可以通过解析字节码得到,参考了 dis 模块的源码: {{{#!python import sys import opcode def get_name(obj): frame = sys._getframe(1) code = frame.f_code.co_code index = frame.f_lasti op = opcode.opname[ord(code[index-3])] oparg = ord(code[index-2]) + ord(code[index-1])*256 if op in ('LOAD_NAME', 'LOAD_GLOBAL'): return frame.f_code.co_names[oparg] elif op == 'LOAD_FAST': return frame.f_code.co_varnames[oparg] else: raise Exception("Can not determine the name of the argument") if __name__ == '__main__': bbb = asdfasdf = {} print get_name(asdfasdf) print get_name(bbb) }}} 输出:: {{{ asdfasdf bbb }}} ##endInc ---- '''反馈''' 创建 by -- ZoomQuiet [<>]