Showing posts from October, 2016

Quick guide to Logging in different files using Python

This is for quick setup of a file logging system 
Step 1: importing the logging module.

import logging

Step 2: Create a logger for yourself. 
logger = logging.getLogger(__name__)

Step 3: Set Logger level

Step 4: Create a handler. 

hdlr = logging.FileHandler(settings.BASE_LOG_FILE, mode='w')

Step 5: Create a formatter

formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')

Step 6: Set formatter and handler

>>> hdlr.setFormatter(formatter) >>> logger.addHandler(hdlr)

When and why to use Classes in Python

Note: All programming done in Python 2.7

Why to make a class?

When we need to use some common variables across other functions quite often . If we only one or 2 functions to write , we should not need to write a class. But if we are going to have 4-5 functions that need to use common objects between themselves, then its better to use classes.

What are class methods?

Class methods are methods that you can call on the class itself

A good example of classes . Lets have a BankAccount class for managing Bank Accounts and its related operations.

classBankAccount(object):#Class methods are methods that you can call on the class itselfdef__init__(self,balance=0):self.balance=balancedefdeposit(self,amount):self.balance+=amountdefwithdraw(self,amount):self.balance-=amount
The __init__ functionis automatically called when a new instance is created. We have two functions that add or subtract  money from account.

Ok....So lets create 2 accounts

Now lets …