getattr возвращает символ '>' вместо mehtod - PullRequest
0 голосов
/ 01 января 2019

У меня есть класс, определенный в 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 голосов
/ 01 января 2019

Я внес небольшие изменения в ваш код, чтобы более четко показать, что происходит:

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(), возможно, в какой-то более ранней итерации кода, и переопределение все еще лежит в пространстве имен вашей сессии оболочки.Если это так, запуск новой сессии интерпретатора только с представленным вами кодом должен решить проблему.

...