Adding method to a class on the fly

askel dummy666 at mail.ru
Fri Jun 22 16:24:22 EDT 2007


On Jun 22, 3:02 pm, John Henry <john106he... at hotmail.com> wrote:
> Hi list,
>
> I have a need to create class methods on the fly.  For example, if I
> do:
>
> class Dummy:
>     def __init__(self):
>         exec '''def method_dynamic(self):\n\treturn
> self.method_static("it's me")'''
>         return
>
>     def method_static(self, text):
>         print text
>         return
>
> 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.
>
> Can that be done?
>
> Thanks,

class Dummy:
  def method(self, arg):
    print arg

def method2(self, arg):
  self.method(arg)

Dummy.method2 = method2
Dummy.method2('Hello, world!')




More information about the Python-list mailing list