16.special methods in classes

SpeciaL Methods

We cannot use general built in functions on the classes.

In the case of Lists

mylist = [1,2,3]
len(mylist)
print(mylist)

Output:
3
[1, 2, 3]

In the case of Classes

class sample():
    pass

mysample = sample()
len(mysample)

print(mysample)

Output:
TypeError: object of type 'sample' has no len()
<__main__.sample object at 0x7f84a10f2310>

__str__() method

Special method str() will be defined in the classes to return string representation of the object.
This method is called when print() or str() function is invoked on an object.

Using __str__() method

class book():

  def __init__(self,title,author):

    self.title = title
    self.author = author
    self.pages = pages

  def __str__(self):
    return f"{self.title} by {self.author}"

b = book('Python Classes','Bhavya')
print(b)

Output:
Python Classes by Bhavya

__len__() method

The len() function will attempt to call a method named __len__() in our class.

Using __len__() method

class book():

  def __init__(self,title,author,pages):

    self.title = title
    self.author = author
    self.pages = pages

  def __str__(self):
    return f"{self.title} by {self.author}"

  def __len__(self):
    return self.pages

b = book('Python Classes','Bhavya', 200)
len(b)

Output:
200

__del__() method

__del__() is a destructor method which is called as soon as all references of the object are deleted i.e when an object is garbage collected.
By using del keyword all references of object will be deleted and therefore destructor invoked automatically.

Using __del__() method

class book():

  def __init__(self,title,author,pages):

    self.title = title
    self.author = author
    self.pages = pages

  def __str__(self):
    return f"{self.title} by {self.author}"

  def __len__(self):
    return self.pages

  def __del__(self):
    print("A book object has been deleted")

  b = book('Python Classes','Bhavya', 200)
  del b

  Output:
  A book object has been deleted

Note

These special methods are called as dunder methods "Double Under (Underscores)" which python will look for to perform special operations.