[Tutor] is it possible to create and amend classes during run-time?

Jerry Hill malaclypse2 at gmail.com
Wed May 2 22:44:54 CEST 2012


On Wed, May 2, 2012 at 3:56 PM, Bjorn Madsen
<bjorn.h.madsen at googlemail.com> wrote:
> Hi,
> I have been studying http://docs.python.org/tutorial/classes.html for a
> while, but still have two questions which I could not answer. Perhaps you
> could help?
>
> Does anyone know if it is possible during run-time to:
> a) add attributes to classes, which will unknown at program start, but
> "emerge" later whilst the program is running?
> b) add subclasses to class (also during runtime)

As far as I understand your questions, the answer to both of those is
yes.  It might help for you to provide an example of exactly what you
mean, though.

Here's a quick examples (python 2.6, from the interactive interpreter)
of adding an attribute to an existing class:

>>> class Foo(object):
	pass

>>> my_foo = Foo()
>>> Foo.bar = True
>>> print my_foo.bar
True
>>>

I defined the class Foo, created an instance of that class, then later
added an attribute to the class itself.  As you'd expect, that
attribute is also visible on the instance.

You second question is a little more difficult to understand.  Classes
don't know about their subclasses, so you wouldn't normally "add a
subclass to a class".  Perhaps if you describe what you're trying to
accomplish, it would be easier to demonstrate how to do it.

-- 
Jerry


More information about the Tutor mailing list