Sunday, April 20, 2025

Dunder / Magic Methods in Python like __init__()

 Tech with Tim in his python video on Dunder methods in python speaks about

1) __init__() method is a constructor                                



class Rect():

    def __init__(self,x,y):

        self.x = x

        self.y = y

        print("Called __init__ with param %s, %s" % (x,y))

Rect(2,3) => calls __init__ method.

2)  + method is same as __add__()

str1 = "hello"                          

str2 = "world"

new_str = str1 + str2

same_str = str1.__add__(str2)

print(new_str)

print(same_str)


3) __length__() is invoked when len(object) is called                  


str1 = "hello"

str2 = "world"

str1_length = len(new_str)

str2_length = len(same_str)

print(str1_length, str2_length)


4)  __add__(self, oper): is invoked on + operator

     __str__(self): is invoked when the object is printed

class Counter():

    def __init__(self):

        self.value = 1

    def count_up(self):

        self.value += 1

    def count_down(self):

        self.value -= 1

    def __str__(self):

        return f"Count=%s"% self.value

    def __add__(self, oper):

        return self.value + oper.value

count1 = Counter()

count2 = Counter()

count1.count_up()

count2.count_up()

print(count1, count2)

print(count1 + count2)

5) __repr__()   - representation

6) __sub__(),    --subtraction

   __mul__(),      -- multiply

  __truediv__()    -- division

7)__lt__()      --Lessthan, 

   __gt__()     --GreaterThan, 

   __eq__(),    -- Equalto    

  __gte__()  -- Greater than equal, 

   __lte__()  -- Less than equal,

   __ne__()  - notequal

8) __getitem__() in lists obj[item] useful for indexing,

   __setitem__() in lists obj[index]= value,

   __delitem__()in lists del obj[index],

I intended to try out all the methods but lack of time is making me post faster

No comments:

Post a Comment