getattr返回字符“>”而不是方法

时间:2019-01-01 15:43:25

标签: python python-2.7 getattr

我在feat.py中定义了一个类

class feat:
  def __init__(self):
    print 'feat init '
    pass


  def do_something(self):
    return true

现在我打以下电话:

from feat import *
f=feat()
for i in dir(f): #feature_functions:
        i_str = str(i)
        print 'f has this attribute',  hasattr(f,i)
        print 'f has  attribute value',  getattr(f,i)

我正在输出:

feat init 
f has this attribute True 
f has attribute value > 

我尝试使用i_str如下所示

print 'f has this attribute',  hasattr(f,i_str)
print 'f has  attribute value',  getattr(f,i_str)

我得到相同的输出。

输出应该不是如下所示吗?

f has this attribute True 
f has attribute value <function do_something at 0x10b81db18>

将感谢您的任何建议。我正在使用Python 2.7。

1 个答案:

答案 0 :(得分:0)

我对您的代码进行了微小的更改,以更清楚地显示正在发生的事情:

from feat import *
f=feat()
for i in dir(f): #feature_functions:
        print i, 'f has this attribute',  hasattr(f,i)
        print i, 'f has  attribute value',  getattr(f,i)

这是我得到的输出:

feat init 
__doc__ f has this attribute True
__doc__ f has  attribute value None
__init__ f has this attribute True
__init__ f has  attribute value <bound method feat.__init__ of <feat.feat instance at 0x0000000004140FC8>>
__module__ f has this attribute True
__module__ f has  attribute value feat
do_something f has this attribute True
do_something f has  attribute value <bound method feat.do_something of <feat.feat instance at 0x0000000004140FC8>>

这是我们俩都期望的。主要区别在于更改后的代码未调用str()。我怀疑您可能已经在代码的某些早期迭代中重新定义了str(),并且重定义仍然存在于Shell会话的名称空间中。如果是这样,仅使用您提供的代码开始全新的解释器会话即可解决该问题。

相关问题