Trouble with generator as method

P

Peter Cole

I'm having difficulty understanding why this doesn't work:

import sys, new, inspect

class T:
def foo(self):
yield 1
yield 2
yield 3


t = T()

ic = t.__class__
for key in ic.__dict__.keys():
if inspect.isfunction(ic.__dict__[key]):
im = new.instancemethod(ic.__dict__[key], t, ic)


print t.foo
print im

print 't.foo().next() = %s' % t.foo().next()
print 'im.next() = %s' % im.next()

<bound method T.foo of <__main__.T instance at 0x00B7ADA0>>
<bound method T.foo of <__main__.T instance at 0x00B7ADA0>>
t.foo().next() = 1

Traceback (most recent call last):
File "D:/python242/Test Scripts/trial.py", line 22, in -toplevel-
print 'im.next() = %s' % im.next()
AttributeError: 'function' object has no attribute 'next'
 
P

Peter Otten

Peter said:
I'm having difficulty understanding why this doesn't work:
import sys, new, inspect

class T:
     def foo(self):
        yield 1
        yield 2
        yield 3


t = T()

im = new.instancemethod(T.foo, t, T)
print t.foo
print im

# prints
# <bound method T.foo of <__main__.T instance at 0x00B7ADA0>>
# <bound method T.foo of <__main__.T instance at 0x00B7ADA0>>

From the output you can see that both are equivalent bound methods.
print 't.foo().next() = %s' % t.foo().next()
print 'im.next() = %s' % im.next()

Yet you call t.foo() while you don't call im.

Peter
 
P

Peter Cole

Peter said:
im = new.instancemethod(T.foo, t, T)


# prints
# <bound method T.foo of <__main__.T instance at 0x00B7ADA0>>
# <bound method T.foo of <__main__.T instance at 0x00B7ADA0>>

From the output you can see that both are equivalent bound methods.


Yet you call t.foo() while you don't call im.

Peter

Right, I've got it now, thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,161
Messages
2,570,892
Members
47,427
Latest member
HildredDic

Latest Threads

Top