Variables vs Objects

Here I will be covering the semantics of variables and objects, which are the main ways you store, reference, and operate on data using Python.

Variables are Pointers
When assigning variables in a language such as C : int x = 5 you are essentially putting the data 4 in a "memory bucket" named x. However in Python variables are thought of not as containers but as pointers. x = 5 As seen above in Python you are essentially defining a pointer named x that points to some other bucket containing the value 4. 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 why people say that Python in dynamically-typed, variable names can point to objects of any type. So in Python you can do things like: x = 5 x = 'Hello World!' x = [2, 4, 8] Whereas in statically-typed languages such as C we must declare the type : int x = 5

The consequence of having this dynamically-typed form is we have to be careful of having two variable names pointing to the same mutable object, then changing one will change the other as well.

Everything is an Object
Python is an object-oriented programming language, and in Python everything is an object. x = 'Hello World!' type(x) str

Python has types; however, the types are linked not to the variable names but to the objects themselves. In object-oriented programming languages like Python, an object is an entity that contains data along with the 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, the 'append' method that is used to add items to lists. This is done using the dot syntax :

some_list = [2, 4, 6] some_list.append(8) print(some_list) [2, 4, 6, 8] Even simple types have attached attributes and methods. For example, numerical types have a real and imag attributes that returns the real and imaginary part of the value, if viewed as a complex number: x = 4.5 print(x.real, '+', x.img, '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 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 Even the attributes and methods of objects are themselves objects with their own type information : type(x.is_integer) builtin_function_or_method