6

Sorry if this is quite noobish to you, but I'm just starting out to learn Python after learning C++ & Java, and I am wondering how in the world I could just declare variables like id = 0 and name = 'John' without any int's or string's in front! I figured out that perhaps it's because there are no ''s in a number, but how would Python figure that out in something like def increase(first, second) instead of something like int increase(int first, int second) in C++?!

2
  • 2
    Just a hint: don't name your variables stuff like "id", it'll override the built in function id(). In Python, functions are first-class objects, so they share the namespace with variables. Commented Mar 15, 2010 at 6:12
  • one thing i learnt from python::boost is that everything, i mean everything in python is from type Object (python Object). Thats how it is possible that an int can be string or char or float or whatever, its all an object and is handled that way. str, int, etc are just derivatives of object and thus can be transformed. Commented Mar 19, 2012 at 20:42

5 Answers 5

13

The literal objects you mention carry (pointers to;-) their own types with them of course, so when a name's bound to that object the problem of type doesn't arise -- the object always has a type, the name doesn't -- just delegates that to the object it's bound to.

There's no "figuring out" in def increase(first, second): -- name increase gets bound to a function object, names first and second are recorded as parameters-names and will get bound (quite possibly to objects of different types at various points) as increase gets called.

So say the body is return first + second -- a call to increase('foo', 'bar') will then happily return 'foobar' (delegating the addition to the objects, which in this case are strings), and maybe later a call to increase(23, 45) will just as happily return 68 -- again by delegating the addition to the objects bound to those names at the point of call, which in this case are ints. And if you call with incompatible types you'll get an exception as the delegated addition operation can't make sense of the situation -- no big deal!

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks to both you and everyone else who contributed! :)
7

Python is dynamically typed: all variables can refer to an object of any type. id and name can be anything, but the actual objects are of types like int and str. 0 is a literal that is parsed to make an int object, and 'John' a literal that makes a str object. Many object types do not have literals and are returned by a callable (like frozenset—there's no way to make a literal frozenset, you must call frozenset.)

Consequently, there is no such thing as declaration of variables, since you aren't defining anything about the variable. id = 0 and name = 'John' are just assignment.

increase returns an int because that's what you return in it; nothing in Python forces it not to be any other object. first and second are only ints if you make them so.

Objects, to a certain extent, share a common interface. You can use the same operators and functions on them all, and if they support that particular operation, it works. It is a common, recommended technique to use different types that behave similarly interchangably; this is called duck typing. For example, if something takes a file object you can instead pass a cStringIO.StringIO object, which supports the same method as a file (like read and write) but is a completely different type. This is sort of like Java interfaces, but does not require any formal usage, you just define the appropriate methods.

1 Comment

Thanks! I would totally upvote you, but unfortunately my daily vote limit has been reached.
6

Python uses the duck-typing method - if it walks, looks and quacks like a duck, then it's a duck. If you pass in a string, and try to do something numerical on it, then it will fail.

Have a look at: http://en.wikipedia.org/wiki/Python_%28programming_language%29#Typing and http://en.wikipedia.org/wiki/Duck_typing

Comments

4

When it comes to assigning literal values to variables, the type of the literal value can be inferred at the time of lexical analysis. For example, anything matching the regular expression (-)?[1-9][0-9]* can be inferred to be an integer literal. If you want to convert it to a float, there needs to be an explicit cast. Similarly, a string literal is any sequence of characters enclosed in single or double quotes.

In a method call, the parameters are not type-checked. You only need to pass in the correct number of them to be able to call the method. So long as the body of the method does not cause any errors with respect to the arguments, you can call the same method with lots of different types of arguments.

2 Comments

(Of course, the actual lexical analysis rules for parsing are a tad more complicated than this.)
Also, to be pedantic, (-)?[1-9][0-9]* would be what a decimal integer literal looks like.
0

In Python, Unlike in C++ and Java, numbers and strings are both objects. So this:

   id = 0
   name = 'John'

is equivalent to:

   id = int(0)
   name = str('John')

Since variables id and name are references that may address any Python object, they don't need to be declared with a particular type.

3 Comments

There are a few things misleading about this post. 1) It is true that ints and strs are objects in Python and the C++ and Java have some primitive types as well as objects, but this is not why you do not have to declare variables in Python. 2) The equivalent code would be id = int(0) and name = str('John'); Number and String are not the names of anything in Python, and it doesn't really clear anything up to rephrase such things, considering this still requires creating int and str objects from literals. 3) "object pointers" is not a technical term in the context of Python AFAIK
Good points, Mike; edits made. The point of replacing literals with constructors, though, is that it is less obvious to a beginner that literals return object references.
I hope it is effective in doing so, though it doesn't really get around the fact that those literals make objects (that are then passed to int and str). Also, welcome to SO! =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.