dynamic type changing
David C. Ullrich
ullrich at math.okstate.edu
Sun May 28 09:11:29 EDT 2006
On 28 May 2006 01:07:16 -0700, andychambers2002 at yahoo.co.uk wrote:
>>> I'm working on a "TempFile" class that stores the data in memory until
>>> it gets larger than a specified threshold (as per PEP 42). Whilst
>>> trying to implement it, I've come across some strange behaviour. Can
>>> anyone explain this?
>
>>> The test case at the bottom starts a TempFile at size 50 and prints its
>>> type. It then increases the size to the threshold at which point
>>> "self" is changed to being a TemporaryFile.
>
>> Changed how ?-)
>
>Just by being assigned with a TemporaryFile object. I thought that if
>you do
>
>instance = TempFile()
>
>that "instance" and "self" defined in the Class were the same thing so
>that if you changed the class of self, the class of instance would also
>change.
>
>Thanks very much for your example. It has solved my problem and helped
>me understand a new pattern at the same time.
Bruno says you _can_ assign to __class__ but calls that "risky".
If you ever do feel the urge to assign a new value to some
object's __class__ it might be a good idea to first make certain
you can predict the behavior of the following:
class A:
msg = 'A'
def hmm(self):
print self.msg
class B:
msg = 'B'
def hmm(self):
print self.msg
x = A()
x.hmm()
x.__class__ = B
x.hmm()
class C:
def __init__(self):
self.msg = 'C'
def hmm(self):
print self.msg
class D:
def __init__(self):
self.msg = 'D'
def hmm(self):
print self.msg
x = C()
x.hmm()
x.__class__ = D
x.hmm()
************************
David C. Ullrich
More information about the Python-list
mailing list