Showing posts with label python_oops. Show all posts
Showing posts with label python_oops. Show all posts

Jan 12, 2019

Python Operator Overloading

#Operator overloading
class operatorOverloadObject:
    def __init__(self, x = 0, y = 0):
        self.x = x
        self.y = y
    
    def __str__(self):
        return "({0},{1})".format(self.x,self.y)
    
    def __add__(self,other): #Fucntion to overload + operator
        x = self.x + other.x
        y = self.y + other.y
        return operatorOverloadObject(x,y)

obj1 = operatorOverloadObject(1, 2)
obj2 = operatorOverloadObject(3, 4)
print(obj1)  #(1,2)
print(obj2)  #(3,4)
print(obj1 + obj2)  #(4,6) 

#Other operations to overload...
#Addition    p1 + p2, p1.__add__(p2)
#Subtraction p1 - p2, p1.__sub__(p2)
#Multiplication  p1 * p2, p1.__mul__(p2)
#Power   p1 ** p2,    p1.__pow__(p2)
#Division    p1 / p2, p1.__truediv__(p2)
#Floor Division  p1 // p2,    p1.__floordiv__(p2)
#Remainder (modulo)  p1 % p2, p1.__mod__(p2)
#Bitwise Left Shift  p1 << p2,    p1.__lshift__(p2)
#Bitwise Right Shift p1 >> p2,    p1.__rshift__(p2)
#Bitwise AND p1 & p2, p1.__and__(p2)
#Bitwise OR  p1 | p2, p1.__or__(p2)
#Bitwise XOR p1 ^ p2, p1.__xor__(p2)
#Bitwise NOT ~p1, p1.__invert__()

Jan 11, 2019

Python Class methods static vs class

#class method demo
class Pets:
    name = "pet animals"

    @classmethod
    def about(cls):
        print("This class is about {}!".format(cls.name))
    
class Dogs(Pets):
    name = "'man's best friends'"

class Cats(Pets):
    name = "cats"

p = Pets() #parent class
p.about() #This class is about pet animals!

d = Dogs() #inherited class
d.about() #This class is about 'man's best friends'!

c = Cats() #inherited class
c.about() #This class is about cats!


#static method demo
class Pets:
    name = "pet animals"

    @staticmethod
    def about():
        print("This class is about {}!".format(Pets.name))   
    
class Dogs(Pets):
    name = "'man's best friends'"

class Cats(Pets):
    name = "cats"

p = Pets()
p.about() #This class is about pet animals!
d = Dogs() 
d.about() #This class is about pet animals!
c = Cats()
c.about() #This class is about pet animals!


Python encapsulation getter setter

#Python OOPS Getter / Setter
class Person(object):
    def __init__(self, p_name=None):
        self._name = p_name

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, new_name):
        if type(new_name) == str: #type checking for name property
            self._name = new_name
        else:
        print 'Error: Invalid type to set'

    @name.deleter
    def name(self):
        del self._name

print '############# Getter/Setter'
p = Person('Mike')
print(p.name)  #Mike
p.name = 'George'  #Grorge
print(p.name)
p.name = 2.3 # Causes an exception, Error: Invalid type to set
print(p.__dict__)  #{'_name': 'George'}
del p.name
print(p.__dict__) #{}

Python Inheritance Detail

#Multiple inheritance
class Base1:
    @classmethod
    def f1(self):
    print  'Base1 f1'
    def f2(self):
    print  'Base1 f2'   

class Base2:
    def f1(self):
    print  'Base2 f1'
    def f2(self):
    print  'Base2 f2'
    def f3(self):
    print  'Base2 f3'   

class MultiDerived(Base1, Base2):
    def f1(self):
    print  'MultiDerived f1'

print '###########Multiple inheritance'
md = MultiDerived()
md.f1()  #MultiDerived f1
md.f2()  #Base1 f2
md.f3()  #Base2 f3
Base1.f1()  #Base1 f1  #classmethod
#Base2.f1()  #fail
#MultiDerived.f1()  #fail


#Multi-level inheritance
class Base:
    def f1(self):
    print  'Base f1'

class Derived1(Base):
    def f1(self):
    print  'Derived1 f1'
    def f2(self):
    print  'Derived1 f2'

class Derived2(Derived1):
    pass

print '###########Multi-level inheritance'
d2 = Derived2()
d2.f1() #Derived1 f1
d2.f2() #Derived1 f2      

Mar 11, 2013

Packages in Python


Today, We discuss about the following :
1) how to create and use a Package in Python with a simple example.
2) Use of __init__.py
3) How to import classes/function and how to use them

Lets take a ride.

Create a folder structure as mentioned below (Where the package name is Package_Sample):
Package_Sample/__init__.py
Package_Sample/A.py
Package_Sample/B.py
Package_Sample/test.py
Package_Sample/sub_folder/C.py
Package_Sample/sub_folder/D.py

Use of __init__.py
In this file, we define the path of all the files & functions to be imported required for the project.
Once you define here, all these classes/functions, you can access directly, we discuss about this in a short while

e.g.,
from A import *
from B import *
from sub_folder.C import *
from sub_folder.D import *

How to use classes defined in __init__.py
Once you have defined in __init__.py
You can directly access functions of C & D (which are in the path Package_Sample/sub_folder/)
Main advantage is that you no need to specify the whole path (sub_folder) again and again.

e.g.,
from Package_Sample import A
from Package_Sample import B
from Package_Sample import C
from Package_Sample import D



Package_Sample/__init__.py

'''
Once you have defined in __init__.py
You can directly access functions of C & D (which are in the path Package_Sample/sub_folder/)
Main advantage is that you no need to specify the whole path (sub_folder) again and again.
'''

from A import *
from B import *
from sub_folder.C import *
from sub_folder.D import *
 


Package_Sample/A.py

class A:
    def __init__(self, type, height, price, age):
        self.type = type
        self.height = height
        self.price = price
        self.age = age
        
    def print_details(self):
        print("\nThis A Type is  :" + self.type + " type ")
        print("This A Height is  :" + self.height + " foot ")
        print("This A Price is   :" , str(self.price) + " dollars ")
        print("This A Age is     :" , str(self.age) + " years")
	 


Package_Sample/B.py

class B:
    def __init__(self, type, height, price, age):
        self.type = type
        self.height = height
        self.price = price
        self.age = age
        
    def print_details(self):
        print("\nThis B Type is    :" + self.type + " type ")
        print("This B Height is    :" + self.height + " foot ")
        print("This B Price is     :" , str(self.price) + " dollars ")
        print("This B Age is       :" , str(self.age) + " years")
        
        	 


Package_Sample/test.py


#Testing __init__.py
from Package_Sample import A 
from Package_Sample import B
from Package_Sample import C
from Package_Sample import D

cfcpiano_A = A("AAAA", "100 Cms", 11000, 10)   #Constructor or Creating Object for Class A
cfcpiano_A.print_details()

cfcpiano_B = B("BBBB", "200 Cms", 22000, 20)   #Constructor or Creating Object for Class B
cfcpiano_B.print_details()

cfcpiano_C = C("CCCC", "300 Cms", 33000, 30)   #Constructor or Creating Object for Class C
cfcpiano_C.print_details()

cfcpiano_D = D("DDDD", "400 Cms", 44000, 40)   #Constructor or Creating Object for Class D
cfcpiano_D.print_details()


	 


Package_Sample/sub_folder/C.py
   
class C:
    def __init__(self, type, height, price, age):
        self.type = type
        self.height = height
        self.price = price
        self.age = age
        
    def print_details(self):
        print("\nThis C Type is  :" + self.type + " type ")
        print("This C Height is  :" + self.height + " foot ")
        print("This C Price is   :" , str(self.price) + " dollars ")
        print("This C Age is     :" , str(self.age) + " years")

    	 


Package_Sample/sub_folder/D.py

class D:
    def __init__(self, type, height, price, age):
        self.type = type
        self.height = height
        self.price = price
        self.age = age
        
    def print_details(self):
        print("\nThis D Type is  :" + self.type + " type ")
        print("This D Height is  :" + self.height + " foot ")
        print("This D Price is   :" , str(self.price) + " dollars ")
        print("This D Age is     :" , str(self.age) + " years")
        	 

How to Run :
Package_Sample/]# python test.py

You may also wish to read Object Oriented Concepts in Python as mentioned :
Python Class and Object Example
Inheritance in Python

Python Class and Object Example

Lets discuss the basic Object-Oriented concept of Class & Object in Python with a simple example.

Lets create a Person Class and create objects for the Person class.


Python_Class_Object.py (Copy the below snippet and run the program)

class Person:
    '''Represents a person.'''
    count = 0

    def __init__(self, name):
        '''Initializing data.'''
        self.name = name
        print('\n Initializing %s' % self.name)

        # To count the people
        Person.count += 1

    def displayName(self):
        ''' Saying Hello'''
        print('My name is %s.' % self.name)
    
    def count_people(self):
        '''Prints the count.'''
        if Person.count == 1:
            print('I am the only person here.')
        else:
            print('We have %d persons here.' % Person.count)

Winston = Person('Winston Churchil')
Winston.displayName()
Winston.count_people()

Abraham = Person('Abraham Lincoln')
Abraham.displayName()
Abraham.count_people()
	 



You may also wish to read Object Oriented Concepts in Python as mentioned :
Inheritance in Python

Inheritance in Python

Lets discuss about Inheritance in Python using an example... Lets take a ride...

Here we consider Vehicle as Parent Class where as Car & Truck are sub-classes which inherit from the Parent class(Vehicle).


class Vehicle:
    '''Represents any Vehicle.'''
    def __init__(self, name, model):
        self.name = name
        self.model = model
        print('Initialized Vehicle: %s' % self.name)
    
    def details(self):
        '''Call my details.'''
        print('Name:"%s" model:"%s"' % (self.name, self.model))

class Car(Vehicle):
    '''Represents a Car.'''
    def __init__(self, name, model, price):
        Vehicle.__init__(self, name, model)
        self.price = price
        print('Initialized Car: %s' % self.name)

    def details(self):
        Vehicle.details(self)
        print('price: "%d"' % self.price)

class Truck(Vehicle):
    '''Represents a Truck.'''
    def __init__(self, name, model, price):
        Vehicle.__init__(self, name, model)
        self.price = price
        print('Initialized Truck: %s' % self.name)
    
    def details(self):
        Vehicle.details(self)
        print('price: "%d"' % self.price)

c = Car('Cooper', 100, 30000)
t = Truck('Jeep', 200, 50000)

print() # prints a blank line

vehicles = [c, t]
for member in vehicles:
    print() # prints a blank line
    member.details() # works for both Cars and Trucks