Pravar Agrawal Technology & Travel

Python Learning Part 5

Continuing from my last post on handling exceptions in Python, I’ll be ndiscussing on Classes today. Classes, are a level of abstraction in Python which can be used to give structure to our programme. Which in-turn results in neat and clean definition of functions inside it. In Python, we define a class in the following way,

>>>class ClassName(parent_class):
	 statement 1
	 statement 2
	 statement 3

In the statements, we can define any variables or class methods for example,

>>> class ClassTest(object):
    	  x = 10
	  y = 20
>>> obj_1 = ClassTest()
>>> dir(obj_1)
'__class__', '__doc__', 'x', 'y']

Above we have defined two variables x & y inside our class and next we created an object of the same class. And when we do a dir on that object we can clearly see the variables defined inside our class.

init in classes is a special method which is also a constructor for classes. A constructor is initialized upon the object creation for a class. Let’s look at the below example,

>>> class Bank(object):

    	   def __init__(self, branch_name, city, bank_name):
          self.branch_name = branch_name
          self.city = city
          self.bank_name = bank_name
          print("The bank object is created")

      def print_info(self):
          print("Name of branch: ", self.branch_name)
          print("City: ", self.city)
          print("Bank Name: ", self.bank_name)

init is called upon the creation of the object of a class. Above, as soon as we’ll create an object we’ll see the message “The bank object is created”. Here, the object is passed on implicitly to every method which is available but we have to get it explicitly in every methods while defining our methods. Also, we need to declare all the possible attributes in the init method itself. And if we are not using any of the values we can declare those as None

>>> bank_obj = Bank()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() takes exactly 3 arguments (1 given)
>>> bank_obj = Bank("Pratap Nagar", "Pathankot", "SBI")
The bank object is created

Let’s try to get other details associated with our object of class Bank,

>>> bank_obj.print_info()
Name of branch: Pratap Nagar
City: Pathankot
Bank Name: SBI

We can also delete an object created previously by following way,

>>> del bank_obj
>>> bank_obj
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'bank_obj' is not defined

We can use properties so as to have more fine control over data attribute access. In the following bank class, we’ll set few properties and see how we can implement that,

>>> class Bank(object):
    def __init__(self, branch_name):
    	self.__branch_code = "SB909"
	self.branch_name = branch_name

    @property
    def branch_code(self):
    	"""
	The branch code for the branch which cannot be in all
	characters
	"""
	return self.__branch_code

    @branch_code.setter
    def branch_code(self, value):
    	for char in value:
	    if ! char.isalpha():
	       print("Sorry you got to have a character in Branch code")
	       return
	    self.__branch_code = value
    if __name__ == '__main__':
       bank_obj = Bank(branch_name="Sanganer")
       bank_obj.__branch_code = "HF001"
       print("Branch code: ", bank_obj.__branch_code)
       bank_obj.__branch_code = "001"
       print("Branch code: ", bank_obj.__branch_code)

Output:

$ python py_bank.py
Branch code: HF001
Sorry you got to have a character in Branch code
Branch code: HF001

Above, we saw how easy is to declare, handle classes in Python. So much fun, right!