Constructors are extremely useful to execute setup code and properly initialize a new instance.
When the programming language creates an instance of a specific class, something happens under the hood. Like: Creates a new instance of the specified type; Allocates the necessary memory; And then executes the code specified in the constructor.
When the runtime executes the code within the constructor, there is already a live instance of the class. Thus, you have access to the attributes and methods defined in the class.
You can use the destructor to perform any necessary cleanup before the object is destroyed and removed from memory. In Python programming languages, when the runtime detects that you aren't referencing an instance anymore and when a garbage collection occurs, the runtime executes the code specified within the instance's destructor.
To count the number of instances of a specific class that are being kept alive: Have a variable shared by all the classes; Customize the class constructor to automatically increase the value for the counter; Customize the class destructor to automatically decrease the value for the counter; This way, you can check the value of this variable to know the objects that are being referenced in your application.
<aside> 💡
Python, in the first place, is a High-level object-oriented programming language
</aside>
Guido van Rossum designed Python according to the first-class everything principle.
Thus, all the types are classes, from the simplest types to the most complex ones: integers, strings, lists, dictionaries, and so on. This way, there is no difference between an integer (int), a string, and a list. Everything is treated in the same way. Even functions, methods, and modules are classes.
int(), str(), float(), list(), tuple()
, and more:# Type of objects
number1 = 12
number2 = 12.5
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)
my_string = "Hello, this is Object-Oriented Programming"
objects = [number1, number2, my_list, my_tuple, my_string]
for obj in objects:
print(type(obj))
Output:
<class 'int'>
<class 'float'>
<class 'list'>
<class 'tuple'>
<class 'str'>
isinstance()
: used to check if the object is a specific type of objects.# Type of objects
number = 12
if isinstance(number, float):
print("True")
else:
print("False")