Ikke's Blog

Archives for: December 2007

Dec 26
Blog moved

This blog is moved. You can find my new blog on http://eikke.com. Thanks for visiting!

Dec 14
Python strangeness

Could someone explain this?

Code:

list = (
    (0, 'foo'),
    (1, 'bar'),
    (2, 'baz'),
)

class Klass:
    def bat(self):
        print '-1'

for l in list:
    if not hasattr(Klass, l[1]):
        print '%s should print %d' % (l[1], l[0])
        def _f(self):
            print l[0]
        _f.__doc__ = 'Get %s' % l[1]
        setattr(Klass, l[1], _f)

k = Klass()
print
print 'Docstrings:'
print 'Foo:', k.foo.__doc__
print 'Bar:', k.bar.__doc__
print 'Baz:', k.baz.__doc__

print

print 'Executed:'
print 'bat:',
k.bat()
print 'foo:',
k.foo()
print 'bar:',
k.bar()
print 'baz:',
k.baz()

print

print 'Locations:'
print 'bat:', str(k.bat.im_func)
print 'foo:', str(k.foo.im_func)
print 'bar:', str(k.bar.im_func)
print 'baz:', str(k.baz.im_func)

Output:

foo should print 0
bar should print 1
baz should print 2

Docstrings:
Foo: Get foo
Bar: Get bar
Baz: Get baz

Executed:
bat: -1
foo: 2
bar: 2
baz: 2

Locations:
bat: <function bat at 0xb7c58e2c>
foo: <function _f at 0xb7c58df4>
bar: <function _f at 0xb7c58f0c>
baz: <function _f at 0xb7c58f44>
$ python -V
Python 2.4.4

Maybe I'm just missing something... Don't flame ;-)

Categories

Who's Online?

  • Guest Users: 158

Misc

XML Feeds

What is RSS?