Category: 2. Special methods

  • Python __del__

    Summary: in this tutorial, you will learn about the Python __del__ special method and understand how it works. Introduction to the Python __del__ method In Python, the garbage collector manages memory automatically. The garbage collector will destroy the objects that are not referenced. If an object implements the __del__ method, Python calls the __del__ method right before the garbage collector destroys the object. However, the garbage…

  • Python __bool__

    Summary: in this tutorial, you will learn how to implement the Python __bool__ method to return boolean values for objects of a custom class. Introduction to the Python __bool__ method An object of a custom class is associated with a boolean value. By default, it evaluates to True. For example: In this example, we define the Person class, instantiate an object, and…

  • Python __hash__

    Summary: in this tutorial, you’ll learn about the Python hash() function and how to override the __hash__ method in a custom class. Introduction to the Python hash function Let’s start with a simple example. First, define the Person class with the name and age attributes: Second, create two instances of the Person class: Third, show the hashes of the p1 and p2 objects: Output: The hash() function accepts an object and returns…

  • Python __eq__

    Summary: in this tutorial, you’ll learn how to use the Python __eq__ method to compare two objects by their values. Introduction to the Python __eq__ method Suppose that you have the following Person class with three instance attributes: first_name, last_name, and age: And you create two instances of the Person class: In this example, the john and jane objects are not the same object. And you can check it using…

  • Python __repr__

    Summary: in this tutorial, you’ll learn how to use the Python __repr__ dunder method and the difference between the __repr__ and __str__ methods. Introduction to the Python __repr__ magic method The __repr__ dunder method defines behavior when you pass an instance of a class to the repr(). The __repr__ method returns the string representation of an object. Typically, the __repr__() returns a string that can be executed and yield the same value…

  • Python __str__

    Summary: in this tutorial, you’ll learn how to use the Python __str__ method to make a string representation of a class. Introduction to the Python __str__ method Let’s start with the Person class: The Person class has three instance attributes including first_name, last_name, and age. The following creates a new instance of the Person class and display it: Output: When you use the print() function to display the instance of the Person class, the print() function…