Some language proposals.

Jimmy Retzlaff jimmy at retzlaff.com
Thu Feb 26 04:18:11 EST 2004


Jacek Generowicz <jacek.generowicz at cern.ch> writes:
>
> >>> class foo: pass
> ...
> >>> class callable:
> ...     def __call__(self): print self
> ...
> >>> instance = callable()
> >>> def meth(self): print self
> ...
> >>> foo.meth = meth
> >>> foo.instance = instance
> >>> f = foo()
> >>> f
> <__main__.foo instance at 0x815fa64>
> >>> f.meth()
> <__main__.foo instance at 0x815fa64>  # self == f
> >>> f.instance()
> <__main__.callable instance at 0x815f624>  # self != f
> >>> f.meth
> <bound method foo.meth of <__main__.foo instance at 0x815fa64>>
> >>> f.instance
> <__main__.callable instance at 0x815f624>  # Hmm, it's not a method
> >>>
> 
> meth behaves like a Python method, instance does not.
>
> Find some way of making callable [from above] use
> types.FunctionType.__get__.  I don't see what code examples could
> possibly help in specifying the problem more clearly (unless the code
> is the solution, of course).

The function new.instancemethod will build an instance method for you,
but your callable needs two selves, one for the instance of callable and
another for the instance of foo so that it can access the state of each:

>>> class foo: pass
...
>>> class callable:
...   def __call__(self_callable, self_foo):
...     print self_callable, self_foo
...
>>> instance = callable()
>>> import new
>>> foo.instance = new.instancemethod(instance, None, foo)
>>> f = foo()
>>> f
<__main__.foo instance at 0x008FAB70>
>>> instance
<__main__.callable instance at 0x008FABE8>
>>> f.instance()
<__main__.callable instance at 0x008FABE8> <__main__.foo instance at
x008FAB70>
>>> f.instance
<bound method foo.? of <__main__.foo instance at 0x008FAB70>>

> But please don't bother unless you really want to do it for your own
> entertainment.

Writing Python code is always entertaining. :)

Jimmy





More information about the Python-list mailing list