Types
Contents
Types#
In Python, everything has a type. These types are used to determine what sort of behaviour objects should have. For example, real numbers have type int
or float
:
type(-33)
int
type(1.32)
float
Similarly, strings have type str
.
type("Hello")
str
Booleans (True
and False
) have type bool
.
type(True)
bool
And turtles have type mobilechelonian.Turtle
.
from mobilechelonian import Turtle
terry = Turtle()
type(terry)
mobilechelonian.Turtle
Because it doesn’t make sense to add turtles together, there is no +
operation for things of type mobilechelonian.Turtle
. Similarly, there is no forward
method for int
. This is what we mean when we say that the type of an object should determine what sort of behaviour it has. This description is not quite accurate, and if you are interested in why you should research “Python duck typing”.
a = 12
a.forward(10)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Input In [6], in <cell line: 2>()
1 a = 12
----> 2 a.forward(10)
AttributeError: 'int' object has no attribute 'forward'
There are many more types in Python, both built-in and in modules like numpy
or mobilechelonian
.
Conversion between types#
We often have objects of one type, that we would prefer to have a different type. For example, we could have the string "1241"
representing the number \(1241\), but if we wish to do any arithmetic on this number we would have problems:
n = "1241"
3 + n
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [7], in <cell line: 2>()
1 n = "1241"
----> 2 3 + n
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Python gives us a TypeError
, telling us that it does not make sense to use the operation +
on types int
and str
. In order to add them, we should first convert n
to an int
:
3 + int(n)
1244
Note that having done int(n)
has not made n
an int
- it just returned
an int
. If we wanted to make n
an int
we should write
n = int(n)
This same idea applies to many types - if you want to convert x
into a particular type some_type
, you should use some_type(x)
. This may or may not work, depending on whether Python has a way of doing the conversion. For example, Python doesn’t know how to convert an int
into a set
:
n = 1241
set(n)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [10], in <cell line: 2>()
1 n = 1241
----> 2 set(n)
TypeError: 'int' object is not iterable
But it does know how to convert a list
into a set
:
set([n])
{1241}
And it knows how to convert a str
into a set
:
s = "Hello World"
set(s)
{' ', 'H', 'W', 'd', 'e', 'l', 'o', 'r'}