7.5 Classes and Objects in Python: Special Methods

In the Python language, everything is an object, including primitive data types. Classes provide a way to package data and functionality together. When creating a new class, we create a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it to maintain its state. Class instances can also have methods (defined by their class) to modify their state.

Special methods are a key feature of Python, allowing you to create classes that behave like built-in data types. This means that you can use special methods to overload standard operators and functions so that they work with your custom classes. These special methods are always surrounded by double underscores (__) and are known as "dunder methods".

__init__ Method

The __init__ method is a special method that is called automatically when an object is created from a class. This method is typically used to perform any necessary initialization. Here is an example:

class MyClass:
  def __init__(self):
    self.data = []

In this example, the __init__ method is used to initialize the data attribute for each new instance of the MyClass class.

__str__ and __repr__ Methods

The __str__ and __repr__ methods are used to provide string representations of an object. The __str__ method is called by the str(obj) function and the print function to convert the object to a string. The __repr__ method is used to provide a string representation that can be used to recreate the object using the eval() function.

class MyClass:
  def __init__(self, name):
    self.name = name

  def __str__(self):
    return f'MyClass({self.name})'

  def __repr__(self):
    return f'MyClass({self.name})'

__eq__ and __ne__ Methods

The __eq__ and __ne__ methods are used to overload the equality and inequality operators. The __eq__ method is called when two objects are compared using the equality operator (==). The __ne__ method is called when the inequality operator (!=) is used.

class MyClass:
  def __init__(self, name):
    self.name = name

  def __eq__(self, other):
    if isinstance(other, MyClass):
      return self.name == other.name
    return False

  def __ne__(self, other):
    return not self.__eq__(other)

Arithmetic Operator Methods

There are several special methods that can be used to overload arithmetic operators, including __add__, __sub__, __mul__, __truediv__, and many others. Each of these methods is called when the corresponding operator is used on objects of the class.

For example, here's how you could overload the addition operator for a class that represents a mathematical array:

class Vector:
  def __init__(self, x, y):
    self.x = x
    self.y = y

  def __add__(self, other):
    if isinstance(other, Vector):
      return Vector(self.x + other.x, self.y + other.y)
    else:
      raise TypeError('Vectors can only be added to other vectors.')

This is just an introduction to special methods in Python. There are many other special methods available that allow you to customize the behavior of your classes in powerful and flexible ways.

Now answer the exercise about the content:

_Which of the following special methods is called automatically when an object is created from a Python class?

You are right! Congratulations, now go to the next page

You missed! Try again.

Article image Classes and Objects in Python: Constructors and Destructors

Next page of the Free Ebook:

42Classes and Objects in Python: Constructors and Destructors

3 minutes

Obtenez votre certificat pour ce cours gratuitement ! en téléchargeant lapplication Cursa et en lisant lebook qui sy trouve. Disponible sur Google Play ou App Store !

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text