Python vs. C#
Duncan Booth
duncan at NOSPAMrcp.co.uk
Tue Aug 12 04:38:56 EDT 2003
"Joe Cheng" <code at joecheng.com> wrote in
news:Jq%Za.8237$M6.632214 at newsread1.prod.itd.earthlink.net:
> Java and C# have static strong typing.
>
> Python has dynamic strong typing. So, if you can keep the types of
> your objects straight without the help of the compiler, you get the
> benefits of a concise syntax while enjoying type safety at runtime.
>
> Someone correct me if I've gotten it wrong...
>
You have it about right. C# lets you define functions that take arguments
of any type by boxing them as objects. However, to perform almost any
operation on these values you have to cast them back to their original
type. So a function that takes two objects and adds them together can't
work unless you know the type you expected the objects to be. You cannot
just add two objects, even if they are of the same type, you have to cast
(unbox) them from object back to their real type (and you have to get that
type *exactly* right, you can't for example unbox a short as an int) and
then operate on them.
[A couple of operations work directly on objects, you can convert any
object to a string, and compare objects for equality directly].
Python on the other hand will let you do something like adding two objects
together, it will perform some permitted conversions automatically, e.g.
extending int to float, but it won't attempt to do weird things like parse
a string into a number, or for that matter automatically convert a number
to a string.
Both languages are strongly typed. The drawback with C# is mainly that you
have to keep telling the language things that both you and the compiler
already know. If I have an ArrayList filled with strings, and I want to
pass one of them to a function taking a string argument, I have to
explicitly cast the element of the ArrayList back to string. If the cast
fails at runtime I get an exception. Why can the compiler not put that cast
in silently and give me the same exception at runtime?
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list