Steven D'Aprano
1/24/2008 9:28:00 PM
On Thu, 24 Jan 2008 12:35:44 -0800, William Pursell wrote:
> Basically, you can
> instantiate an object A of class Foo, and later change A to be an object
> of class Bar. Does Python support this type of flexibility? As I
> stated above, I've been away from Python for awhile now, and am a bit
> rusty, but it seems that slots or "new style" objects might provide
> this type of behavior.
If you think slots are a candidate for this functionality, I think you
have misunderstood what slots actually are. Slots don't define what class
the object has, they are a memory optimization for when you need vast
numbers of instances and don't need arbitrary attributes.
> The ability to have an object change class is
> certainly (to me) a novel idea. Can I do it in Python?
Yes, mostly. Example:
>>> class Spam(object):
.... def whatami(self):
.... return "I am a delicious and tasty processed meat product"
....
>>> class Parrot(object):
.... def whatami(self):
.... return "I am a colourful bird with a large vocabulary"
....
>>>
>>> s = Spam()
>>> s.whatami()
'I am a delicious and tasty processed meat product'
>>> s.__class__ = Parrot
>>> s.whatami()
'I am a colourful bird with a large vocabulary'
If you actually play around with this, you'll soon find the limitations.
For instance:
>>> s.__class__ = int
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __class__ assignment: only for heap types
--
Steven