"casting" Python objects

David LeBlanc whisper at oz.net
Thu May 23 13:07:04 EDT 2002


> -----Original Message-----
> From: python-list-admin at python.org
> [mailto:python-list-admin at python.org]On Behalf Of djw
> Sent: Wednesday, May 22, 2002 20:08
> To: python-list at python.org
> Subject: Re: "casting" Python objects
>
>
> > 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

Close, but no cigar... :-)

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

class b:
	def handler(self):
		print "Class b"

x = a()	# x is an a
x.handler()

x = b()	# x is a b
x.handler()

x = "foo"	# x is a string
print x

The type of the variable is the type of whatever it happens to have in it,
not what it's allowed to have in it as in more type constrained languages.

If you have to have method names that differ by message type, then subclass
the message classes to have a commonly named method like handler that calls
the type-specific method. FWIW, you might want to look into inheritance and
polymorphism :-)

Regards,

Dave LeBlanc
Seattle, WA USA






More information about the Python-list mailing list