python improvements (Was: Re: New Language)

Bernhard Herzog herzog at online.de
Wed May 17 08:01:19 EDT 2000


Mikael Olofsson <mikael at isy.liu.se> writes:

> On 16-May-00 Bernhard Herzog wrote:
>  >  emile at fenx.com writes:
>  >  
>  > > It looks like you can sneak your way into a class:
>  > > 
>  > > class Pass:
>  > >   None
>  > > 
>  > > class Test:
>  > >   def __init__(self, a,b,c,d,e):
>  > >     self.f = f(a,b,c,d,e)
>  > >   def func(self, a):
>  > >     print "This is a class function (call ref: %s)" % a
>  > > 
>  > > a = Pass()
>  > > a.__class__ = Test
>  > > 
>  > > a.func('class')
>  >  
>  >  Heh, that's a sneaky way to instantiate a class without actually
>  >  instantiating it.
> 
> I thought that Emile pointed out a bug, but you obviously seem to 
> understand what's going on. Could you share your insight?

One part of the problem I described earlier was that I couldn't
instantiate a class at one point in the program because I didn't have
the necessary parameters for the constructor yet. However, I wanted to
call a method on that class. A class method would have been a solution.

In Emile's code, that uninstantiable class is Test. To create an
instance of that class Emile used a dummy class Pass, created an
instance of that, a, and made that instance an instance of Test by
assigning to its __class__ attribute. Now you can call the func method
on that instance as if it were a Test instance.

There's one potential problem with this, of course. a doesn't have any
instance variables that func might expect, but in this case it works
because func doesn't use any instance variables at all.


Hmm, it just occurred to me that there is a relatively simple way to
treat a method as a class method:

>>> class C:
..     def f(x):
..             print x
.. 
>>> C.f.im_func(100)
100

This even works when f is an inherited method, but it relies on some
internals.


-- 
Bernhard Herzog   | Sketch, a drawing program for Unix
herzog at online.de  | http://sketch.sourceforge.net/



More information about the Python-list mailing list