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

Prasad, Ramit ramit.prasad at jpmorgan.com
Wed May 2 22:56:10 CEST 2012


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

Typically unless you need it to be shared across instances (like 
a singleton pattern) you would probably add it to the instance 
instead of the class. So the first answer is Yes.

Like Jerry, I am not sure what you mean by adding a subclass. 
Rather than misinterpret I will just wait for you to clarify.

Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  


More information about the Tutor mailing list