Basic Python Semantics: Variables and Objects - jude-lindale/Wiki GitHub Wiki
Python Variables Are Pointers
To assign variables is done by putting a variable name to the left of an equals (=
) sign.
# assign 4 to the variable x
x = 4
you are essentially defining a pointer named x
that points to some other bucket containing the value 4
. Note one consequence of this: because Python variables just point to various objects, there is no need to "declare" the variable, or even require the variable to always point to information of the same type! This is the sense in which people say Python is dynamically-typed: variable names can point to objects of any type. So in Python, you can do things like this:
x = 1 # x is an integer
x = 'hello' # now x is a string
x = [1, 2, 3] # now x is a list
If we have two variable names pointing to the same mutable object, then changing one will change the other as well! For example, let's create and modify a list:
x = [1, 2, 3]
y = x
An additional example:
x = 10
y = x
x += 5 # add 5 to x's value, and assign it to x
print("x =", x)
print("y =", y)
x = 15
y = 10
When we call x += 5
, we are not modifying the value of the 10
object pointed to by x
; we are rather changing the variable x
so that it points to a new integer object with value 15
. For this reason, the value of y
is not affected by the operation.
Everything is an Object
Earlier we saw that variables are simply pointers, and the variable names themselves have no attached type information. This leads some to claim erroneously that Python is a type-free language. But this is not the case! Consider the following:
x = 4
type(x)
int
x = 'hello'
type(x)
str
x = 3.14159
type(x)
float
Python has types; the types are linked not to the variable names but to the objects themselves.
an object is an entity that contains data along with associated metadata and/or functionality. In Python everything is an object, which means every entity has some metadata (called attributes) and associated functionality (called methods). These attributes and methods are accessed via the dot syntax.
For example, before we saw that lists have an append
method, which adds an item to the list, and is accessed via the dot (".
") syntax:
L = [1, 2, 3]
L.append(100)
print(L)
[1, 2, 3, 100]
Numerical types have a real and imag attribute that returns the real and imaginary part of the value, if viewed as a complex number:
x = 4.5
print(x.real, "+", x.imag, 'i')
4.5 + 0.0 I
Methods are like attributes, except they are functions that you can call using opening and closing parentheses. For example, floating point numbers have a method called is_integer
that checks whether the value is an integer:
x = 4.5
x.is_integer()
False
x = 4.0
x.is_integer()
True