strong/weak - dynamic/static [Was: Getting started]

Mark McEahern marklists at mceahern.com
Thu Sep 19 13:21:17 EDT 2002


[Henrik Motakef]
> There's a difference between a type and a class, I guess...

Alex made the point already, but the following code demonstrates that what
you demonstrated relies on old-style classes, which gives you a misleading
answer imho:

**

class foo(object):

    def changeme(self, newclass):
        self.__class__ = newclass

class bar(object):

    pass

f = foo()
b = bar()

print "type(f) = %s" % type(f)
print "type(b) = %s" % type(b)
print "type(f) == type(b) ==> %s" % (type(f) == type(b))

f.changeme(bar)

try:
    # Try to change back...
    f.changeme(foo)
except AttributeError:
    print "Whaddya know, we can't change f anymore."

print "type(f) = %s" % type(f)
print "type(b) = %s" % type(b)
print "type(f) == type(b) ==> %s" % (type(f) == type(b))

**

Output:

type(f) = <class '__main__.foo'>
type(b) = <class '__main__.bar'>
type(f) == type(b) ==> 0
Whaddya know, we can't change f anymore.
type(f) = <class '__main__.bar'>
type(b) = <class '__main__.bar'>
type(f) == type(b) ==> 1

**

My point in posting this is merely to counter the false claim that you
cannot change an object's type at runtime.  I'm not asserting that you can
change any object's class to anything whatsoever without experiencing
problems or runtime errors, of course.

Cheers,

// m

-





More information about the Python-list mailing list