How to code dynamically created methods?
socyl at 987jk.com.invalid
Wed Jun 20 15:55:09 CEST 2007
Nevermind, I found the problem...
In <f5bb99$2jr$1 at reader2.panix.com> kj <socyl at 987jk.com.invalid> writes:
>I've tried a bazillion ways to code dynamically generated methods,
>to no avail.
>The following snippet is a very simplified (and artificial) demo
>of the problem I'm running into, featuring my latest attempt at
>this. The idea here is to use __getattr__ to trap any attempt to
>invoke a nonexistent method, have it return a generic handler called
>_auto which creates the new method dynamically, invokes it, and
>"installs" it in the class, so that subsequent calls to the same
>method go directly to the newly created method, instead of to
>__getattr__. It is this last step, the "installation" of the new
>method, that is giving me problems.
>class A( object ):
> def __getattr__( self, name ):
> self._auto_name = name
> return self._auto
> def hello( self, name ):
> print "hi! my name is %s" % name
> def _auto( self, *args ):
> name = self._auto_name
> def m( self, *args ): self.hello( name )
> m( self, *args )
> m = classmethod( m )
> setattr( A, name, m )
>x = A()
>x.foo() # ok
>x.foo() # bombs
>>>> reload(test) hi! my name is foo Traceback (most recent call
> File "<stdin>", line 1, in ? File "test.py", line 19, in ?
> x.foo() File "test.py", line 12, in m
> self.hello( name ) TypeError: unbound method hello() must be
>called with A instance as first argument (got str instance instead)
>I'm sure that the problem is with my naive attempt to add a method
>to class A dynamically (in the last two lines of the definition of
>_auto). What's the right way to do this?
>NOTE: In my address everything before the first period is backwards;
>and the last period, and everything after it, should be discarded.
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.
More information about the Python-list