object vs class oriented -- xotcl

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Fri Jan 25 07:55:40 EST 2008


Steven D'Aprano a écrit :
> On Thu, 24 Jan 2008 12:35:44 -0800, William Pursell wrote:
> 
>> The ability to have an object change class is
>> certainly  (to me) a novel idea.  Can I do it in Python?
> 
> Yes, mostly. Example:
> 
(snip)
> 
> 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
> 

Other limitations may appear with frameworks relying on metaprogramming 
features for their inner working so users don't have to worry about 
boilerplate - something you'll often find in recent web frameworks, orms 
etc...

Mostly, the point with dynamically changing the class of an object 
(whether or not your in the above situation) is that you must ensure 
consistant state by yourself, which sometimes happens to be far less 
trivial than it seems at first look. I once tried to implement the State 
pattern this way (in real-life code), and while it worked, it ended 
being more complicated (and brittle) than implementing it the canonical 
way. So while it *may* be a good solution, I'd advise you to carefully 
check the concrete use case before using this feature.



More information about the Python-list mailing list