What is an object?
Object oriented programming is one of the most popular programming paradigms of the modern day with languages like C++, Javascript, and Python. It focuses mainly on classes and objects. Let’s focus on object.
What is id and type?
Simply put, id and type are built-in Python functions that return the identifier and type of an object respectively. The function id returns what is also known as a memory address, while type returns the name of the type of object.
$ python3
>>>
>>> a = 2
>>> id(a)
10105120
>>> type(a)
<class 'int'>
Mutable and Immutable objects
Mutable simply stands for objects that can be changed or altered. Immutable objects are objects that cannot be changed, altered, or manipulated by normal conventions. All of the primal variables are considered immutable in Python. Tuples and strings also fall in this category. The most common mutable object is the list. Sets and dictionaries are also immutable. This is an important to distinguish for us developers to correctly implement objects that we want to remain the same always, and others that are subject to change.
Functions and arguments
Functions, ironically enough, are objects within Python. Functions in Python are known as first-class objects, which means they can be assigned to a variable, and item in any list or collection, and passed as an argument to another function. Essentially you have an object, taking objects as arguments, because everything is an object.
In most languages there is a clear distinction between what is known as passing by value and passing by reference. In Python that distinction is not so clear. Python uses a system known as “call by object reference” or “call by assignment”.
- Parameters to functions are references to objects, which are passed by value.
- When you pass a variable to a function, Python passes the reference to the object to which the variable refers to. Not the variable itself.
- If the value passed in a function is immutable, the function does not modify the variable.
- If the value passed is mutable, the function may modify the variable in-place.
Advanced Topics
CPython
The implementors of CPython decided that it is good to have 262 integers pre-allocated at anytime for performance. These are defined from the macros NSMALLPOSINTS and NSMALLNEGINTS. They are arrays of integers. The range is from -5 to 256. These are considered the most commonly used integer values.
#define NSMALLPOSINTS 257
#define NSMALLNEGINTS 5
Aliasing
In Python, aliasing is essentially a second name for an object. For example
>>> a = [dog, cat, 7]
>>> b = a
>>> b
[dog, cat, 7]
Variable b in this case is aliased. Changes made to one alias, affects the other.