Skip to main content

Python Classes and Objects

******** OBJECT ORIENTED PROGRAMMING IN PYTHON ********

OBJECT: Objects are the basic run-time entities in an object-oriented system, They may represent a person, a place, a bank account, a table of data or any item that the program must handle.

CLASS: A class is a special data type which defines how to build a certain kind of object.The class also stores some data items that are shared by all the instances of this class
class student:
    “““A class representing a student ”””
 def __init__(self , n, a):        
   self.full_name = n     
   self.age = a
 def get_age(self):  #Method     
   return self.age

The following program shows the How to initialize the members in Class, How to create Instances for particular Object and finally How to print existed data

class Student:
# Initializing the variables
	def __init__(self,name,age):
		self.fullname=name
		self.sage=age
# Display the entered data such as Students name and age
	def display(self):
		print 'Student FullName: %s' %(self.fullname)
		print 'Stuent Age: %d'%(self.sage)
# S1,S2 and S3 objects 
# S1,S2 and S3 are three different student details and age
s1=Student('Python',14)
s1.display()
s2=Student('Jython',23)
s2.display()
s3=Student('Objects',45)
s3.display()

=== Encapsulation and Abstraction in Python ===

-> Encapsulate means to hide. Encapsulation is also called data hiding.You can think Encapsulation like a capsule (medicine tablet) which hides medicine inside it. Encapsulation is wrapping, just hiding properties and methods. Encapsulation is used for hide the code and data in a single unit to protect the data from the outside the world. Class is the best example of encapsulation. Abstraction refers to showing only the necessary details to the intended user. As the name suggests, abstraction is the "abstract form of anything". We use abstraction in programming languages to make abstract class. Abstract class represents abstract view of methods and properties of class. In programming languages, encapsulation is used to refer to one of two related but distinct notions, and sometimes to the combination thereof: A language mechanism for restricting access to some of the object's components. A language construct that facilitates the bundling of data with the methods (or other functions) operating on that data.

=== PUBLIC, PROTECTED AND PRIVATE MEMBERS BEHAVIOR ===

>>> x = Encapsulation(11,13,17) 
>>> x.public
 11 
>>> x._protected 
13 
>>> x._protected = 23 
>>> x._protected 
23 
>>> x.__private 
	Traceback (most recent call last): 
		File "", line 1, in 
	 AttributeError: 'Encapsulation' object has no attribute '__private‘
 >>> 

=== Inheritance in Python ===

The Python feature most often associated with object-oriented programming is inheritance. Inheritance is the ability to define a new class that is a modified version of an existing class. The primary advantage of this feature is that you can add new methods to a class without modifying the existing class. It is called inheritance because the new class inherits all of the methods of the existing class. Extending this metaphor, the existing class is sometimes called the parent class. The new class may be called the child class or sometimes subclass.

===== SAMPLE CODE FOR BASIC INHERITANCE =====

class Person(object):
	def __init__(self,name,age):
		self.name=name
		self.age=age
	def show(self):
		print 'Person Name: %s' %(self.name)
		print 'Person Age: %s' %(self.age)
class Employe(Person):
	def __init__(self,name,age,company,sal):
		self.company=company
		self.sal=sal
		super(Employe,self).__init__(name,age)
	def __repr__(self):
		return str (self.name+self.age+self.company+self.sal)
	def showme(self):
		super(Employe,self).show()
		print 'Company Name: %s'%(self.company)
		print 'Employe Salary per Annum: %s' %(self.sal)
		print '\n'
		
empdict={'guido':['45','PYTHON','500000'],'van':['25','JYTHON','200000'],'rossum':['35','ABC','400000']}
for key,value in empdict.iteritems():
	print key,value
	emp=Employe(key,value[0],value[1],value[2])
	emp.showme()

=== POLYMORPHISM in Python ===

Polymorphism is something similar to a word having several different meanings depending on the context. In object-oriented programming, polymorphism (from the Greek meaning "having multiple forms") is the characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow an entity such as a variable, a function, or an object to have more than one form. The classic example is the Shape class and all the classes that can inherit from it (square, circle, irregular polygon, splat and so on). With polymorphism, each of these classes will have different underlying data. A point shape needs only two co-ordinates (assuming it's in a two-dimensional space of course). A circle needs a center and radius. A square or rectangle needs two co-ordinates for the top left and bottom right corners (and possibly) a rotation. An irregular polygon needs a series of lines.

=====SAMPLE CODE FOR POLYMORPHISM =====

class Person:
    def __init__(self, name):    
        self.name = name
    def designation(self):              
        raise NotImplementedError("Subclass must implement abstract method")
class Employe(Person):
    def designation(self):
        return 'Software Engineer‘
class Doctor(Person):
    def designation(self):
        return 'Cardiologist‘
class Student(Person):
	def designation(self):
		return 'Graduate Engineer'
persons = [Employe('Guido Van Rossum'),Doctor('Chalapathi'),Student('Robert')]
for person in persons:
    print person.name + ': ' + person.designation()

Comments

Popular posts from this blog

Python Sets and Dictionaries

Python Sets Python Maps examples A mapping object maps hashable values to arbitrary objects. Mappings are mutable objects. There is currently only one standard mapping type, the dictionary. Dictionaries consist of pairs (called items) of keys and their corresponding values. Dictionaries can be created by placing a comma-separated list of key: value pairs within curly braces Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples. Python Set Operations and methods Python Set methods continueed >>> SET={'new','old','list','new'} >>> SET set(['new', 'old', 'list']) Lets play with set operations, it is more like school math here... >>> s={1,2,3,4} >>> k={3,4,5,6} >>> len(s) 4 >>> len(k) 4 >>> 1 in s True >>...

AWS Auto Scaling using Python Boto3

Auto Scaling Group in AWS configure using Python Boto3  What is Auto Scaling means?  This is key capability or power of Cloud Computing Engineers believe in their skills on scaling abilities.  Amazon EC2 Auto Scaling helps to maintain application availability and lets automatically add or remove EC2 instances using scaling policies that we define.  There are 2 types of scaling policies : Dynamic or predictive. These scaling policies let us add or remove EC2 instances capacity to service established or real-time demand patterns. It contains various steps involved in Auto Scaling process using Python Boto3 we will explore every step that accumulate to form a complete automation solution for a DevOps project. ASG Groups associated with ELB and EC2 instances   Understanding AWS Auto scaling configuration steps Check any running instances Create launch configuration Configure ASG for Auto scaling Verify the configuration Disable Auto Scaling In order to setup A...

Importing modules

What is Python Module? When a Python shell starts it only has access to a basic python functions (“int”, “dict”, “len”, “sum”, “range”, ...) “Modules” that contain additional functionality more methods, more reusability and more sharability. Use “import” keyword to tell the Python shell to load a module. import os, sys Namespaces are one honking great idea -- let's do more of those! (Zen of Python) import this Why importing modules in Python? The major advantage comes when you split your program into several files for easier maintenance. How to import modules in Python A module can be imported by another program to make use of its functionality. This is how we can use the Python standard library as well You can import multiple modules. import module1[, module2[,... moduleN] Normally after module import we can use its containing functions by calling them with refering with the module name followed by period or dot(.) and the function/procedure name. import...