Adding method to a class on the fly

John Henry john106henry at hotmail.com
Fri Jun 22 17:44:54 EDT 2007


On Jun 22, 2:28 pm, askel <dummy... at mail.ru> wrote:
> On Jun 22, 5:17 pm, 7stud <bbxx789_0... at yahoo.com> wrote:
>
>
>
> > On Jun 22, 2:24 pm, askel <dummy... at mail.ru> wrote:
>
> > > class Dummy:
> > >   def method(self, arg):
> > >     print arg
>
> > > def method2(self, arg):
> > >   self.method(arg)
>
> > > Dummy.method2 = method2
> > > Dummy.method2('Hello, world!')
>
> > Traceback (most recent call last):
> >   File "test1.py", line 8, in ?
> >     Dummy.method2('Hello, world!')
> > TypeError: unbound method method2() must be called with Dummy instance
> > as first argument (got str instance
> > instead)
>
> > >I like that to be the same as:
>
> > >class Dummy:
> > >    def __init__(self):
> > >        return
>
> > >    def method_dynamic(self):
> > >        return self.method_static("it's me")
>
> > >    def method_static(self, text):
> > >        print text
> > >       return
>
> > >so that I can do:
>
> > >dum=Dummy.method_dynamic()
>
> > >and see "it's me" printed.
>
> > When are you able to see that?
>
> there is no way to call instance method from static one. but in your
> case you can make something like:
>
> class Dummy:
>   @staticmethod
>   def method(arg):
>     print arg
>
> def method2(arg):
>   Dummy.method(arg)
>
> Dummy.method2 = staticmethod(method2)
> Dummy.method2('Hello, world!')
>
> - OR -
>
> def method2(cls, arg):
>   cls.method(arg)
>
> Dummy.method2 = classmethod(method2)
> Dummy.method2('Hello, world!')



Thanks for the response.

The above doesn't exactly do I what need.  I was looking for a way to
add method to a class at run time.

What does work, is to define an entire sub-class at run time.  Like:

class DummyParent:
    def __init__(self):
        return

    def method_static(self, text):
        print text
        return

text = "class Dummy(DummyParent):"
text += "\n\t" + "def __init(self):"
text += "\n\t" + "\tDummyParent.__init__(self)"
text += "\n\t" + "def method_dynamic(self):"
text += "\n\t" + "\tself.method_static(\"it's me\")"

exec text

dum=Dummy().method_dynamic()


Thanks again.




More information about the Python-list mailing list