interesting bound-built-in-method technique
Thomas Malik
malik.thomas at lbbw.de
Fri Jan 19 09:49:19 EST 2001
Chris Ryland wrote:
>
> Reading the Quixote sources taught me an interesting little "hack"
> using bound-built-in methods:
>
> >>> m = {'foo': 1, 'bar': 0}.has_key
> >>> m('foo')
> 1
> >>> m('bar')
> 0
>
> Is this a common idiom in Python? Very clever for turning a dictionary
> lookup into a functional form.
>
> Are there other clever but generally obscure idia? (Idioms? ;-)
How about 'wanna-be' class functions ? like static member functions in
C++ (where you don't need a this/self object) ?
class A:
def __init__(self, name):
self.name = name
def __str__(self):
return self.__class__.__name__ + ':' + self.name
def makeA(name): # 'factory' method. Note: no self argument
return A(name)
class B(A):
pass
# call through method's im_func attribute
a = A.makeA.im_func('a')
# sometimes, it's useful to call a given class's method with some
provided 'self'
print B.__bases__[0].__str__.im_func(a)
More information about the Python-list
mailing list