Showing posts with label oops. Show all posts
Showing posts with label 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__()

Jun 29, 2013

Inheritance in Perl

Inheritance with an Example using Perl

Inheritance:
Inheritance is nothing but inheriting methods/properties from Parent class to child class.
Inheritance is one of main pillars of Object Oriented Concepts.

Inheritance in Perl :
In Perl, inheritance is accomplished by placing the names of parent classes into a special array called @ISA
The elements of @ISA are searched left to right for any missing methods.

E.g.,
our @ISA = qw(AAA BBB);
#This represents we are inheriting from Packages AAA and BBB respectively.

 Lets define with an example as mentioned below :

Inventory.pm (Parent of Pen)
Pen.pm           (Pen inherits methods from Inventory)
main.pl            (Create instance of Pen and accessing the methods of Inventory class as well)


Inventory.pm

#!/usr/bin/perl

package Inventory;

use strict;
use warnings;
use Data::Dumper;

sub new {
    my($class)  = shift;
    my(%params) = @_;
    bless {
       "NUMBER"    => $params{"NUMBER"},
       "QUANTITY" => $params{"QUANTITY"}
    }, $class;
}

1;  


Pen.pm

#!/usr/bin/perl

package Pen;

use strict;
use warnings;
use Data::Dumper;

use Inventory;

our @ISA = qw(Inventory);    #### Inheritance

sub new {
    my($class) = shift;
    my(%params) = @_;

    #my($self) = Inventory->new(@_);
    my($self) = new Inventory(@_);

    $self->{"COLOR"} = $params{"COLOR"};
    return(bless($self, $class));
}

1;
  

main.pl

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;
use Pen;

my $pen = new Pen(
        "NUMBER"   => "12A-34",
        "QUANTITY" => 34,
        "COLOR"    => "blue"
        );

print("The part number is " . $pen->{'NUMBER'}   . "\n");
print("The quantity is "    . $pen->{'QUANTITY'} . "\n");
print("The ink color is "   . $pen->{'COLOR'}    . "\n");
  

Output:
The part number is 12A-34
The quantity is 34
The ink color is blue


Jun 28, 2013

Package or Class Example in Perl

Packages or Classes in Perl (OOPS Concept)

Definition :
In Perl, a class is corresponds to a Package.
To create a class in Perl, we first build a package.
A package is a self-contained unit of user-defined variables and subroutines, which can be re-used over and over again.
They provide a separate namespace within a Perl program that keeps subroutines and variables from conflicting with those in other packages.

Rules to be followed for a module in Perl :
The module in perl in general terms means a namespace defined in a file. Certain modules are only collections of function. In perl the modules must follow the following guidelines:
- The file name of a module must the same as the package name.
- The general naming convention of naming a package is to begin with a capital letter, but not mandatory always.
- All the file name should have the extension of "pm".
- Last line of a package is 1 i.e., returning always 1 as mentioned in the example below.
- In case no object oriented technique is used the package should be derived from the Exporter class.
- Also if no object oriented techniques are used the module should export its functions and variables to the main namespace using the @EXPORT and @EXPOR_OK arrays.
The use directive is used to load the modules.

Creating/Defining Object :
To create an instance of a class (an object) we need an object constructor.
This constructor is a method defined within the package.

What is Bless : 
You create a hash object and bless the hash object to who ever calling the constructor (new method) of a package/class.

E.g.,
Blessing an object based on the parameters passed to the constructor method
my $self = {
        _firstName => shift,
        _lastName  => shift,
        _ssn       => shift,
    };
 bless $self, $class;

Blessing an empty object is also possible
my $self = {};
bless $self , $class

E.g.,
Package Person;
sub new {
    my $class = shift;
    my $self = {
        _firstName => shift,
        _lastName  => shift,
        _ssn       => shift,
    };
    bless $self, $class;
    return $self;
}
1;

Creating Instance of Object :
In order to access package level methods, you need to create object of that class and then start accessing package level variables/methods.

my $object = new Person( "David", "Johnson", 23234345);
In the above example, we are creating object of Person from main.pl, here we are passing required parameters and the constructor (new method) of Person class will return a formatted hash object.

You can even bless an empty hash object as well.        
In case of empty object, the following returns empty object
my $object = new Person();

E.g.,
use Person;
use Data::Dumper;
my $object = new Person( "David", "Johnson", 23234345);

print "\n Person Object is : " . Dumper($object);

Information Hiding : 
This should not allow the users from modifying the object data.
You should allow the users to access the core object using setter/getter methods, there by achieving hiding object data from outside the world.

Let's see the below example for better understanding :
Support.pm has defined some getter(setFirstName) and setter(getFirstName) for accessing firstName
main.pl is accessing the firstName using getter(setFirstName) and setter(getFirstName)

support.pm

#!/usr/bin/perl

package support;

use strict;
use warnings;
use Data::Dumper;

sub new
{
    my $class = shift;
    print "\nClass Name : " . $class;
    my $self = {
        _firstName => shift,
        _lastName  => shift,
        _ssn       => shift,
    };
    # Print all the values just for clarification.
    print "\nFirst Name is $self->{_firstName}";
    print "\nLast Name is $self->{_lastName}";
    print "\nSSN is $self->{_ssn}";
    bless $self, $class;
    return $self;
}

sub setFirstName {
    my ( $self, $firstName ) = @_;
    $self->{_firstName} = $firstName if defined($firstName);
    return $self->{_firstName};
}

sub getFirstName {
    my( $self ) = @_;
    return $self->{_firstName};
}

1;
  

main.pl

#!/usr/bin/perl
use support;

use strict;
use warnings;
use Data::Dumper;

my $object = new support( "David", "Johnson", 23234345);

# Get first name which is set using constructor.
my $firstName = $object->getFirstName();

print "\n\nBefore Setting First Name is : $firstName";

# Now Set first name using helper function.
$object->setFirstName( "Mohd" );

# Now get first name set by helper function.
$firstName = $object->getFirstName();

print "\nAfter Setting First Name is : $firstName\n";  


Output :

Class Name : support
First Name is David
Last Name is Johnson
SSN is 23234345

Before Setting First Name is : David
After Setting First Name is : Mohd