In Python, everything is an object, including values of basic primitive types such as integers, strings, and floats. Objects in Python have attributes and methods that can be accessed using the dot syntax.

Let’s start by looking at an example. Suppose we define a new variable age of type int:

age = 8

Now age has access to the properties and methods defined for all int objects. For instance, we can access the real and imaginary parts of this number using the real and imag attributes:

print(age.real) # 8
print(age.imag) # 0

Additionally, int objects have methods that can be called. For example, we can use the bit_length() method to determine the number of bits necessary to represent the number in binary notation:

print(age.bit_length()) # 4

Similarly, different types of objects have different sets of methods available. For example, a variable holding a list value can use methods like append() and pop():

items = [1, 2]
items.append(3)
items.pop()

The methods available depend on the type of the value.

You can also use the id() function to inspect the location in memory of a particular object. For example:

id(age) # 140170065725376

The memory address of an object can change if you assign a different value to the variable:

age = 8
print(id(age)) # 140535918671808

age = 9
print(id(age)) # 140535918671840

However, if you modify the object using its methods, the memory address remains the same:

items = [1, 2]
print(id(items)) # 140093713593920

items.append(3)
print(items) # [1, 2, 3]
print(id(items)) # 140093713593920

The memory address only changes if you reassign the variable to a different value.

It’s also important to note that some objects in Python are mutable, meaning they can be modified, while others are immutable, meaning they cannot be changed. This behavior depends on the object itself. For example, an int object is immutable. There are no methods to change its value. If you increment the value of an int using age = age + 1 or age += 1, you will find that age points to a different memory location. The original value has not mutated; we have simply switched to another value.

Understanding objects, their attributes, and methods is essential for effectively working with Python. By leveraging the power of objects in your code, you can create more efficient and organized programs.

Tags: Python, objects, attributes, methods, mutability