Adding method to a class on the fly

attn.steven.kuo at gmail.com attn.steven.kuo at gmail.com
Fri Jun 22 18:52:28 EDT 2007


On Jun 22, 2:44 pm, John Henry <john106he... at hotmail.com> wrote:
> On Jun 22, 2:28 pm, askel <dummy... at mail.ru> wrote:
>

(snipped)

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


I'm not sure what you mean by this.  Bind an attribute -- a method --
to class Dummy if and only if an instance of this class is created?



> 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.


I tend to avoid exec if possible.  Also, you
seem to be a bit inexact with regard to the
term "static".


class Dummy(object):
    def __init__(self):
        new_method_name = 'method_dynamic'
        try:
            getattr(Dummy, new_method_name)
        except AttributeError:
            print "Creating an instance method..."
            def newf(self):
                """Something Descriptive Here"""
                return self.method_static("it's me")
            newf.__name__ = new_method_name
            setattr(Dummy, new_method_name, newf)
    def method_static(self, text):
        """I hate this name.  Do not confuse this with a staticmethod;
        what you probably meant was that this is an attribute (a
method)
        bound within the class body as opposed to elsewhere"""
        print text
        return # is this necessary?

d1 = Dummy()
d1.method_dynamic()
d2 = Dummy()
d2.method_dynamic()
print d1.method_dynamic.im_func.__name__
print d1.method_dynamic.im_func.__dict__
print d1.method_dynamic.im_func.__doc__
print d1.method_dynamic.im_func.__module__
print d1.method_dynamic.im_self

--
Hope this helps,
Steven




More information about the Python-list mailing list