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

Tuesday, February 25, 2025

Python Decorators

These features of python are not in any order of importance as such.

I chanced upon a youtube video where "the python dude" was explaining decorators.

It seems like in python we can pass function names as parameter.

Also the passed function can be called from the called function.

Hence our code becomes more useful and more difficult to understand.

import time

def measure_time(func):
    def wrapper():
        start = time.time()
        func()
        end = time.time()
        print(f'Execution time : {end - start} sec')
    return wrapper

@measure_time
def morning():
    print("Good morning")

morning()

Output:

pythonprgms>python pythonprgm5.py 

Good morning

Execution time 0.000936 sec

A similar program with two decorator per function morning is possible:

#It happens because the decorator runs the function immediately.
# The wrapper prevents that and ensures it only runs when you call it.

import time

def measure_time(func):
    def wrapper():
        start = time.time()
        func()
        end = time.time()
        print(f'Execution time : {end - start} sec')
    return wrapper

def greeting(func):
    def wrapper():
        print(f'Hello,')
        func()      
    return wrapper


@greeting
@measure_time
def morning():
    print("Good morning")

morning()

Output:
pythonprgms>python pythonprgm6.py Hello, Good morning
Execution time 0.000936 sec

Similar changes post we can pass arguments to morning function but decorators too need to 
pass same arguments.

# *args , **kwargs
import time

def measure_time(func1):
    def wrapper(*args , **kwargs):
        start = time.time()
        func1(*args , **kwargs)
        end = time.time()
        print(f'Execution time : {end - start} sec')
    return wrapper

def greeting(func2):
    def wrapper(*args , **kwargs):
        print(f'Hello,')
        func2(*args , **kwargs)      
    return wrapper


@greeting
@measure_time
def morning(name):
    print("Good morning %s" % name)

morning("John P Diaz")

Output:
pythonprgms>python pythonprgm7.py Hello, Good morning John P Diaz Execution time : 0.0 sec

Friday, January 17, 2025

Python Dictionaries

 A dictionary in python can contain name value pairs. Like

thisdict = {
    "name" : "Shiva",
    "gender" : True,
    "age" : 45,
}

where thisdict contains name, gender and age of string, boolean and int data type.

On purpose I have created another dict with a JSON as a value of a name-value pair.

thisdict = {
    "name" : "Shiva",
    "gender" : True,
    "age" : 45,
    "assets-json" : {
        "net-worth": 1000000,
        "house-type": "flat",
        "address": ["J P Nagar 5th Ph",
                    "Bangalore",
                    "560034"]
    }
}

I have made use of this dictionary structure in a program which

a. finds the length of the dictionary

b. prints the name, gender and age

c. prints the net-worth of the individual in the dictionary object.


thisdict = {
    "name" : "Shiva",
    "gender" : True,
    "age" : 45,
    "assets-json" : {
        "net-worth": 1000000,
        "house-type": "flat",
        "address": ["J P Nagar 5th Ph",
                    "Bangalore",
                    "560034"]
    }
}

thatdict = {
    "name" : "Harish",
    "gender" : True,
    "age" : 54,
    "assets-json" : {
        "net-worth": 10000000,
        "house-type": "Individual House",
        "address": ["Jayanagar",
                    "Bangalore",
                    "560045"]
    }
}

def length_of_dict(dict_param):
    return len(dict_param)

def display_dict(dict_param):
    print("this dict is of %s" % dict_param["name"])
    gender = "male" if dict_param["gender"] == True else "female"
    print("Age = %s \nGender= %s" %(dict_param["age"], gender))
    print("Net Worth:%s" % dict_param["assets-json"]["net-worth"])

if __name__=="__main__":
    print("Length of thatdict:",length_of_dict(thatdict))
    print("Length of thisdict:",length_of_dict(thisdict))
    display_dict(thatdict)
    display_dict(thisdict)

Output of the program:

Length of thatdict: 4

Length of thisdict: 4

this dict is of Harish

Age = 54

Gender= male

Net Worth:10000000

this dict is of Shiva

Age = 45

Gender= male

Net Worth:1000000

Wednesday, January 1, 2025

Python Lists

 In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe stored at different locations.

  • List can contain duplicate items.
  • List in Python are Mutable. Hence, we can modify, replace or delete the items.
  • List are ordered. It maintain the order of elements based on how they are added.
  • Accessing items in List can be done directly using their position (index), starting from 0.

nested lists in python : matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Access element at row 2, column 3
print(matrix[1][2])

Another program to find pair of numbers in a sorted array that sum to a value(target):

def pair_sum_sorted_all_pairs(arr, target):

  """

  Finds all pairs in a sorted array that sum to a given target.

  Args:

    arr: A sorted array of integers.

    target: The target sum.

  Returns:

    A list of tuples representing the pairs.

  """

  result = []

  left, right = 0, len(arr) - 1

  while left < right:

    current_sum = arr[left] + arr[right]

    if current_sum == target:

      result.append((arr[left], arr[right]))

      left += 1

      right -= 1

    elif current_sum < target:

      left += 1

    else:

      right -= 1


  return result


if __name__=="__main__":

    arr = [1, 2, 3, 4, 5, 6, 7]

    target = 8

    print(pair_sum_sorted_all_pairs(arr, target))

When we run this program here we get following output:


C:\Users\kamat>python untitled123.py

[(1, 7), (2, 6), (3, 5)]

Friday, December 27, 2024

Python - Basics

I have written three python programs in increasing order of complexity.

First one is:

x=int(input("Enter a number"))
y=int(input("Enter another number"))
z=int(input("Enter third number"))
sum=x + y + z
print(sum)


The program reads three numbers (Integers) and finds their sum

class simple:
    def simple_one():
        print("Hello mukesh")
        print("Hello manjunath")


if __name__=="__main__":
    simple.simple_one()


This next program creates a simple class and calls a method on the class object.
The if statement equates __name__ to "__main__" and executes the method if so.

class simple():
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def simple_one(self):
        print("Hello %s %s"%(self.name,self.age))

if __name__=="__main__":
    s = simple("mukesh",45)
    s.simple_one()

This next program above instantiates an object of
class simple by calling its constructor. Then a
method simple_one() on the created object.

Monday, November 18, 2024

Full Stack Development using Python

DJango Web Framework:

It is a free and open source framework for making web applications using python. It is claimed to be a

batteries included framework.

It includes the Admin Site, An Object Relational Mapper(ORM), Authentication, Caching etc.

A Web Application works by having a Front end(Browser/Client) and a Backend(Server).

Recently the trend has been to have the server expose a set of server api endpoints and supply only the data. This data can be either in XML or JSON format.

Front end could be a React/Vue/Angular project.


We cannot compare DJango with React or Vue as they both work at the front end and DJango

is a server technology. A better comparison would be between django and ASP.net core or Express.

We could however use DJango to build the server APIs.

Here is a list of Questions you can pose to the students(VTU):

Laboratory Component:

1. Installation of Python, Django and Visual Studio code editors can be demonstrated.

2. Creation of virtual environment, Django project and App should be demonstrated

3. Develop a Django app that displays current date and time in server

4. Develop a Django app that displays date and time four hours ahead and four hours before as an offset of current date and time in server.

5. Develop a simple Django app that displays an unordered list of fruits and ordered list of selected students for an event

6. Develop a layout.html with a suitable header (containing navigation menu) and footer with copyright and developer information. Inherit this layout.html and create 3 additional pages: contact us, About Us and Home page of any website.

7. Develop a Django app that performs student registration to a course. It should also display list of students registered for any selected course. Create students and course as models with enrolment as ManyToMany field.

8. For student and course models created in Lab experiment for Module2, register admin interfaces, perform migrations and illustrate data entry through admin forms.

9. Develop a Model form for student that contains his topic chosen for project, languages used and duration with a model called project. 

10. For students enrolment developed in Module 2, create a generic class view which displays list of students and detailview that displays student details for any selected student in the list.

11. Develop example Django app that performs CSV and PDF generation for any models created in previous laboratory component.

12. Develop a registration page for student enrolment as done in Module 2 but without page refresh using AJAX.

13. Develop a search application in Django using AJAX that displays courses enrolled by a student being searched. 

You can download the Lab Manual (PDF) from Here: https://drive.google.com/file/d/1MtkObE3iD7kD05cTQcnAwDT298rhXTRf/view?usp=sharing