What are Python Methods and Dunder Methods? A Simple and Effective Introduction to the Functions and Special Behaviors of Classes and Objects

Python 201 object oriented programming method and dunder

Python object-oriented programming methods are functions that define the behavior of a class or an object. They can be either instance methods, which are associated with a specific object and can access its attributes, or class methods, which are associated with the class itself and can only access class attributes. Methods are defined inside a class using the def keyword, followed by the method name and parameters. For example, this is how you can define a method called greet in a class called Dog:

class Dog:
  def init(self, name):
    self.name = name

  def greet(self):
    print(f"Hello, my name is {self.name}.")

Python dunder methods are special methods that have two underscores at the beginning and end of their names. They are also called magic methods or special instance methods. They are used to implement certain behaviors or functionalities for a class or an object, such as operator overloading, string representation, initialization, and destruction. For example, the init method is a dunder method that is called when an object is created. The str method is a dunder method that returns a human-readable string representation of an object. Here is how you can define these dunder methods in the Dog class:

class Dog:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def greet(self):
    print(f"Hello, my name is {self.name} and I am {self.age} years old.")

  def __str__(self):
    return f"{self.name} ({self.age})"

d1 = Dog("Corgi", 8)

print(d1) # Corgi (8)
d1.greet() # Hello, my name is Corgi and I am 8 years old.

In this example, the Dog class has one OOP method, greet(), and one Dunder method, __str__(). The greet() method is used to print the name and age of the dog. The __str__() method is used to return a string representation of the dog.

When you print the p1 object, the __str__() method is called automatically. This is why the output includes the dog’s name and age.

Related posts

Leave a Comment