Nice way to cast a homogeneous tuple

Steven D'Aprano steve-REMOVE-THIS at cybersource.com.au
Thu Jul 29 02:24:36 EDT 2010


On Wed, 28 Jul 2010 22:45:19 -0700, John Nagle wrote:

[...]
>> if you have an instance of class A, you can do this:
>>
>> a = A()  # make an instance of class A
>> a.__class__ = B  # tell it that it's now class B
>>
>> and hope that it won't explode when you try to use it :/
[...]
>     The main use for that sort of thing is in constructing objects
> without their cooperation.  "copy" and "pickle" do that, as they build
> up objects without running their initializers.

True, but there are other use-cases as well, such as the recipe for ring 
buffer which made it into the Python Cookbook. I think this is it:

http://code.activestate.com/recipes/68429-ring-buffer/


> Storing into "__class__"
> may not be portable across Python implementations.  The implications for
> multiple inheritance are difficult. It's really a hack for CPython.

I believe that it is intended as a language feature, not an 
implementation-specific hack:

http://bytes.com/topic/python/answers/449635-assigning-self-__class__


While it's an advanced technique that isn't terribly common, I don't see 
any reason to avoid it.


-- 
Steven



More information about the Python-list mailing list