Yes int
is a class (and it's also called a type; see Python : terminology 'class' VS 'type'), and doing int('123')
returns an instance of an int
object.
However, (in standard Python aka CPython) for small integers (in the range -5 to 256, inclusive) the int
constructor doesn't actually build a new integer object. For efficiency reasons the interpreter has a cache of small integers and the constructor simply returns a reference to the existing int
object. This topic is discussed in the answers to “is” operator behaves unexpectedly with integers.
Your book that calls int()
"the int
method" is being a tiny bit sloppy, IMHO. Pedantically speaking, int
itself is a class, which is a callable object, and when you call a class that call gets automatically converted into a call to the class's constructor method (that is, its __new__
method). But informally it's common to refer to int()
as a function call or method call.
I almost forgot about the question in your first paragraph. When we write
[1, 2, 3]
the interpreter creates the 3 int
objects and puts them inside a fresh list
instance. (To be more precise, it puts references to the int
objects into the list).
Using the standard dis
module you can disassemble the bytecode for this operation:
from dis import dis
dis('a=[1,2,3]')
output
1 0 LOAD_CONST 0 (1)
3 LOAD_CONST 1 (2)
6 LOAD_CONST 2 (3)
9 BUILD_LIST 3
12 STORE_NAME 0 (a)
15 LOAD_CONST 3 (None)
18 RETURN_VALUE
So even though we're "just" creating a literal list it's still a fully-fledged list
instance object. Unlike some OOP languages, Python doesn't have any "primitive" datatypes that aren't objects, so literal integers and literal strings are also objects. Thus a literal string comes equipped with all the standard string methods. Eg,
print('hello'.lower)
output
built-in method lower of str object at 0xb72e7880>
shows us that the literal string 'hello'
has the standard lower()
method.