Skip to main content

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.


class BankAccount(object):
    #Class methods are methods that you can call on the class itself
    def __init__(self, balance=0):
        self.balance = balance
    def deposit(self, amount):
        self.balance += amount
    def withdraw(self, amount):
        self.balance -= amount

The __init__ function is 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


a_account = BankAccount()
b_account = BankAccount()

Now lets deposit something in these accounts


>>> a_account.deposit(100)
>>> b_account.deposit(500)


Let's try to transfer some fund from B to A account. We need to add a "transfer" function to our class.


def transfer(self, other_account, amount):
    self.withdraw(amount)
    other_account.deposit(amount)


>>> b_account.transfer(a_account, 100)
>>> a_account.balance
200
>>> b_account.balance
400

As you can see, how we used classes to perform simple operations between two different accounts.

Customize looks of your object

We can have more control over our objects . Like if we print our object , what will it look.
Normally it looks like this.


>>> a_account
<__main__.BankAccount object at 0x0000000001FB3B38>

We want to show some other info when someone calls up the object itself at the time it is created. We can use the __repr__ function for this.

Lets add this function to our class .


def __repr__(self):
    return "Bank_Account Balance={}".format(self.balance)

One thing to note:

 if __repr__ is defined, and __str__ is not, the object will behave as though __str__=__repr__.

Find more info here 


>>> a_account = BankAccount(1000)
>>> a_account
Bank_Account Balance=1000

If we want to control how it will look when its printed , we should use the __str__ method.


def __str__(self):  # When the object is printed or str(object) is used
    return "Bank_Account is ${}".format(self.balance)


What is Super Class

You might have seen before the keyword being used inside classes. Super here helps us call the original base class __init__function . Whenever I have a method to call in the original baseclass.


class NamedBankAccount(BankAccount):
    def __init__(self, name, *args, **kwargs):
        self.name = name
        super(NamedBankAccount, self).__init__(*args, **kwargs)

Now we create an object of above class.


>>> a = NamedBankAccount('Arc', 1000)
>>> a.name
'Arc'
>>> a.balance
1000
>>> print a
Bank_Account is $1000



As you can see, the 'balance' was auto created by the __init__ of BankAccount class.

Note: In python 3, you can use super().__init__()   . This is much simpler.

Lets add a hello function in our base class and lets add that in our Child class.


class BankAccount(object):
    #Class methods are methods that you can call on the class itself
    def __init__(self, balance=0):
        self.balance = balance
    def deposit(self, amount):
        self.balance += amount
    def withdraw(self, amount):
        self.balance -= amount
    def transfer(self, other_account, amount):
        self.withdraw(amount)
        other_account.deposit(amount)
    def __repr__(self):
        return "Bank_Account Balance={}".format(self.balance)
    def __str__(self):  # When the object is printed or str(object) is used
        return "Bank_Account is ${}".format(self.balance)
    def hello(self):
        print 'Hi'



class NamedBankAccount(BankAccount):
    def __init__(self, name, *args, **kwargs):
        self.name = name
        super(NamedBankAccount, self).__init__(*args, **kwargs)
        super(NamedBankAccount, self).hello()


>>> a = NamedBankAccount(name='Arc')
Hi

I think this is sufficient proof enough that we can call ANY method using super. It just a convenience provided by python.

Note: Just remember that the same can be achieved simple like this, 


BankAccount.__init__(self, 234)

>>> a = NamedBankAccount(name='Arc')
>>> a
Bank_Account Balance=234


Popular posts from this blog

Why should you visit Kashmir sooner?

"If there is paradise on Earth, this is it"
And paradise it was . Early winter is the perfect time to plan for a visit to Kashmir. We will suggest to keep your itinerary  short . And enjoy the best trip of your life. 

   My Visit Month : Mid November 2015

As we were flying close to Srinagar, about 20 minutes before landing , all of a sudden , every passenger in the aircraft was on his toes craning theirs necks over the tiny window to catch a glimpse of the above. A fleet of Snow Giants.


   Visit Meena Bazaar in Dal Lake
  You will find a floating village with houses , shops, and hotels on all kinds of boats.


    A night on a House Boat




Take a Shikara ride.Watch the super clear reflection of the mountain. Spot fishes and water birds.



Take a 2 day stay in Pahalgam. Visit Mini Switzerland first day on a horse ride.


Visit Sonemarg. Enjoy the snow.



On your way to Pahalgam, visit apple orchids . Taste all kind of apples. The golden ones are supposed to be the best.



The dark ominous mou…

Kerala : How to plan for a lifetime's experience

I have been planning this for months and it finally came along in the best time. A full stretch Kerala trip with Kanyakumari as an added bonus. I will not tell you what to do, but HOW to do it. How to plan your dream Kerala Trip. 

Caution: Mine was too comprehensive. Needs high energy and will be quite tiring. 

I chose the monsoon theme..I wanted to be in the middle of the action. This is the only place in India which offers monsoon as a tourism opportunity. I was lucky. I expected super heavy rains. Instead. I ended up right in between the rainy season and summer which was Perfect.

Advantages in travelling in mid AugustRainfall almost over.Waterfalls at their fullest.Greenery all over the state.Backwaters, beach sides and rivers all very clean.Abundant coconuts to enjoy.Hotel rates brought down.Less crowd everywhere.Festive Preparation going on.Shopping becomes pocket friendly.Our route map:






Day 1 Day 2 Day 3 Day 4 Day 5 Day 6

CNTLM in Office

If you are facing a proxy problem , CNTLM is a general option everybody considers. But the working of CNTLM is not always guaranteed. I myself get confused every time I need to use it.

What problem are we actually talking about?

While working in offices and restricted environments where firewalls and other invisible barriers stop your requests from going out, you sometimes need a way to temporarily jump over that barrier to get your job done . Example: You might face them while trying to install using pip in command line, trying to clone a personal git repository. 

What is CNTLM exactly?

I think this is best answered by the creator himself. Refer this. You can download it from here. For configuration, you an refer this. There are many uses of CNTLM but I am trying to solve my own problem here. So I will stick to breaking office barriers for now ;) .

Why do I need to use it :
1) Python package installations using PIP
2) Git operations : Cloning and pushing to server.

Here are a set of steps I …