Dec
26
Ikke's Blog
Archives for: December 2007
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
- All
- Life (56)
- Technology (131)
- Coding Corner (64)
- Docbook (7)
- Summer of Code 06 (0)
- Desktop (93)
- Ivman (3)
- Linux (90)
- Networks (14)
- Coding Corner (64)
Archives
- December 2007 (2)
- November 2007 (3)
- October 2007 (2)
- September 2007 (3)
- August 2007 (4)
- May 2007 (2)
- April 2007 (4)
- March 2007 (5)
- February 2007 (2)
- January 2007 (3)
- July 2006 (1)
- June 2006 (3)
- More...
Who's Online?
- Guest Users: 158