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 Interview Questions -Coding Snipets

 This post is dedicated for all DevOps Engineer, Software Engineers who are preparing for Coding Interviews,  Overview of Coding Interviews Most Companies looking for People with minimum Coding knowledge. In a coding interview, you will be given a small problem to solve within 10 - 20 minutes online screen or in-person on their system. In the question, you might be having some part of the code framed and you might be asked to write a snippet of code in between. You need to understand the code comments and proceed to build the expected snippet of code. Bigger companies look for the General purpose questions, where small companies look for specific questions. The General questions would be like this: Determine if the given word is a palindrome or not. (Example madam) Determine given number is prime or not. How to prepare for a coding interview? Now we have the flexibility to choose the programming language on which you are comfortable.  In general DevOps Infra guys will be ...

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 >>...

Program Controls and loops in Python

Python Programming controls The flow of program will be controlled with conditional statements where this flow  if condition if-else condition if-elif condition while loop while - else loop for loop for with if- else loop if condition Here I would like to work on program control statements, wherein relate some operating system functionalities so that, this would give some basic prototype for the sys admin scripts. #!/usr/bin/python # This illustrate if condition # Filename : ifex.py import os d=os.listdir('/home/pavanbsd/pybin') print d f='ifex.py' if f in d: print "File exists" else: print "Not found..." if-elif-else ladder No worries, coming soon... When you need the task that need to be done repeatedly then your choice is using loops. Python provides two simple loop constructs easy to use! More powerful then other scripting compare to, it has 'else' block. while loop Understand the power of while loop,...