Computer Science · Ch 5 — Getting Started with Python
Everything is an Object
Everything is an Object
Python treats every value or data item as an object — whether it is numeric, a string, or of any other type (the types themselves are discussed in the next section). "Object" here means the value can be assigned to a variable or passed to a function as an argument; every piece of data in a Python program has this status.
Every object has an identity
Each object in Python is assigned a unique identity (ID), which remains the same for the lifetime of that object. This ID is akin to the memory address of the object. The built-in function id() returns the identity of an object:
>>> num1 = 20
>>> id(num1)
1433920576 # identity of num1
>>> num2 = 30 - 10
>>> id(num2)
1433920576 # same identity as num1 — both refer to the object 20
This is the textbook's Example 5.2, and it demonstrates something subtle: num2 was produced by the arithmetic 30 - 10, yet its identity equals that of num1. Both variables refer to the same object — the integer 20 — so id() reports the same number for both. (The actual ID value differs from machine to machine; what matters is that the two calls return the same value.)
Objects in the OOP sense
In the context of Object Oriented Programming (OOP), objects are representations of the real world — an employee, a student, a vehicle, a box, a book, and so on. In any object-oriented language such as C++ or Java, each object has two things associated with it:
- data, also called attributes, and
- behaviour, also called methods.
OOP further builds on the concepts of classes and class hierarchies, from which objects can be instantiated. Those concepts, however, are not in the scope of the present discussion.