"casting" Python objects

djw dwelch91 at attbi.com
Wed May 22 23:07:33 EDT 2002


> you're thinking in a strongly typed manner - but python is dynamicly
typed.
> the variable msg is not typed. it can hold any object, including
subclasses
> of your Message class - no cast needed.
> thats why some people speak of 'bind an object to a name' rather than
> 'assign a value to a variable'.


Hmmmm... I don't think I understand when you say "variable 'msg' has no
type"...

Here is my simple analogous example:

class a:
    def a(self):
        print "a"

class b(a):
    def b(self):
        print "b"

>>>x=a()  # analogous to jabber.Message
>>>x.b() # analogous to FooMsg
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
AttributeError: a instance has no attribute 'b'

To me, this clearly shows that 'x' is of type 'a', not of type 'b'. I agree
that I can then easily do this:

>>> x=b()
>>> x.b()
b

So, yes, x can dynamically change types to another type, but it can only be
_one_type_at_a_time! Right???


In my original post, the Queue was put() with types of jabber.Message. When
you get() them from the Queue, they come off as type jabber.Message. In
order to call a FooMsg method on a message, their type must somehow be
changed to type FooMsg (or something like that).

So, to continue my above example:

>>> import Queue
>>> q = Queue:Queue()
>>> x=a()
>>> q.put(x)
>>> y=q.get()
>>> y.b()
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
AttributeError: a instance has no attribute 'b'

Fails because 'y' is of type 'a' not of type 'b'

Somebody please correct me if I'm wrong here!

:-)

D







More information about the Python-list mailing list