[英]getattr is returning character '>' instead of mehtod
我在 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。
我对您的代码进行了细微更改,以更清楚地显示正在发生的事情:
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 会话的命名空间中。 如果是这样,仅使用您提供的代码开始新的解释器会话应该可以解决问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.