"casting" Python objects
Chris Liechti
cliechti at gmx.net
Wed May 22 19:48:21 EDT 2002
"DJW" <dwelch91 at home.nospam.com> wrote in
news:achcu0$j62$1 at news.vcd.hp.com:
> I know there is no such thing in Python as C-style casting, but I
> don't understand what idiom is supposed to be used instead.
>
> Here's the situation: I'm using jabber.py (in a worker thread) to
> recieve and send messages for my application. When messages arrive
> within jabber.py, a message is created of type jabber.Message and
> placed in a Queue by my connection object.
> In the main thread, I have a sub-class of jabber.Message, call it
> "FooMsg" (there are actually going to be multiple derived types of
> jabber.Message). My main application thread has a loop that pulls
> messages off the Queue and calls the appropriate handler inside of the
> message. However, the type of the messages are of type jabber.Message,
> not my FooMsg that contains the handlers:
>
>
> class FooMsg( jabber.Message):
>
> def Handler( self ):
> # call approriate handler for message
> ...
>
> while 1:
> msg = msg_queue.get() # returns type jabber.Message
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'.
> msg.Handler() # ERROR: Handler() is only in type FooMsg!!!
simple solution: if you want to "Handle" all messages, why not put that
method in all classes, i.e. in the base class?
or simple too: try to call it and see what happens:
try:
msg.Handler()
except AttributeError:
pass
or use hasattr:
if hasattr(msg, "Handler"):
msg.Handler()
chris
--
Chris <cliechti at gmx.net>
More information about the Python-list
mailing list