Hi,
just an expansion on Brian's query, is there a variant of getattr for instance methods?
i.e. class DBRequest:
def __init__(self, fields, action):
self.get(fields)
def get(self, fields):
print fields
Instead of self.get in _init__, the value of action to call a function? Or, is it going to have to be dictionary dispatch?
I don't understand your example, but instance methods are attributes too, so getattr() works with them as well as simple values.
An instance method is an attribute of the class whose value is a function. When you access the attribute on an instance you get something called a 'bound method' which holds a reference to the actual function and a reference to the instance (to pass to the function as the 'self' parameter). You can call a bound method just like any other function. So:
>>> class foo: ... def __init__(self): ... self.bar = 3 ... def baz(self): ... print self.bar ... >>> f=foo()
getattr() of a simple attribute: >>> getattr(f, 'bar') 3
getattr() of an instance method returns a 'bound method': >>> getattr(f, 'baz') <bound method foo.baz of <__main__.foo instance at 0x008D5FD0>>
Calling the bound method (note the added ()) is the same as calling the instance method directly: >>> getattr(f, 'baz')() 3
Of course you can do the same thing with dot notation for attributes: >>> b=f.baz >>> b <bound method foo.baz of <__main__.foo instance at 0x008D5FD0>> >>> b() 3
Kent
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor