Monday, April 3, 2023

Static in Python

Instance variables

They are declared inside a method or the constructor of a class. Their values vary from object to object.

Class variables

They are declared inside the class, but outside all method definitions. They are shared among all instances of a class. They are allocated memory when an object for the class is created for the first time. They can be accessed by either using objects or class name.

Instance methods

They are specific to each object. They can access both class variables and instance variables. They use self as the first parameter. They can be called only using the object of the class.

Class methods

They are shared among all objects of the class. They can access only class variables. They use cls as the first parameter. They can be called using ClassName or by using a class object. They are mostly used as factory methods.

Static methods 

They are also shared among all objects of the class. They cannot access any variable of a class. They do not take any extra parameter. They can be called using ClassName or by using a class object. They are mostly used as utility methods.

class Student:

    # class variables

    school_name = 'ABC School'


    # constructor

    def __init__(self, name, age):

        # instance variables

        self.name = name

        self.age = age


    # instance method

    def show(self):

        print(self.name, self.age, Student.school_name)


    @classmethod

    def change_School(cls, name):

        cls.school_name = name


    @staticmethod

    def find_notes(subject_name):

        return ['chapter 1', 'chapter 2', 'chapter 3']

Static methods are useful in creating Utility functions.


Decorator

A decorator is a function that takes another function as an argument and extends its behavior without explicitly modifying it. eg: for logging, debugging, authentication, measuring execution time, and many more. 

def decorator(func):

  def wrapper():

    print("This is printed before the function is called")

    func()

    print("This is printed after the function is called")  

  return wrapper

This decorator function is called by adding @decorator above the actual function. eg: @staticmethod, @classmethod, @property (for getter/setter). Its main function is to support code reusability.


Iterator

It is a way of iterating over iterable objects like lists, tuples, dicts, and sets.

tup = ("apple", "banana", "cherry")

itr = iter(tup)

print(next(itr))

print(next(itr))

print(next(itr))


Generator

Generators are functions used to create iterators. These functions use one or more yield statements instead of return.

def seq(x):

    for i in range(x):

        yield i      

range_ = seq(4)

print(next(range_))

print(next(range_))

print(next(range_))

print(next(range_))

Generator functions are more memory efficient than normal functions.

No comments: