Wednesday, June 30, 2021

Python - Inheritance & more on OOPs

 Inheritance is a way of creating a new class from an existing class.

Syntax:

class Emoloyee: #Base Class

#Code

class Programmer(Employee): #Derived or child class

#Code

We can use the methods and attributes of Employee in Programmer object. Also, we can overwrite or add new attributes and methods in the Programmer class.


Type of Inheritance:

  • Single inheritance
  • Multiple inheritance
  • Multilevel inheritance

Single Inheritance

Single inheritance occurs when child class inherits only a single parent class.

Base -> Derived


Multiple Inheritance:

Multiple inheritance occurs when the child class inherits from more than one parent class.

Multilevel Inheritance

When a child class becomes a parent for another child class.


Super() method

Super method is used to access the methods of a super class in the derived class.

super().__init__()  #Calls constructor of the base class


Class methods

A class method is a method which is bound to the class and not the object of the class.

@classmethod decorator is used to create a class method.

Syntax to create a class method:

@classmethod

def (cls, p1, p2):

#code

@property decorators

Consider the following class

class Employee:

@property 

def name(self):

return self.ename

if e = Employee() is an object of class employee, we can print (e.name) top print the ename/call name() function.


@.getters and @.setters

The method name with @property decorator is called getter method.

We can define a function + @name.setter decorator like below:

@name.setter

def name(self, value):

self.ename = value

Operator overloading in Python

Operators in python can be overloaded using dunder methods.

These methods are called when a given operator is used on the objects.

Operators in python can be overloaded using the following methods:

p1 + p2 -> p1.__add__(p2)

p1 – p2 -> p1.__sub__(p2)

p1 * p2 -> p1.__mul__(p2)

p1 / p2 -> p1.__truediv__(p2)

p1 // p2 -> p1.__floordiv__(p2)

Other dunder/magic methods in Python

__str__() -> used  to set what gets displayed upon calling str(obj)

__len__() -> used to set what gets displayed upon calling .__len__() or len(obj)

 

Practice:

Create a class C-2d vector and use it to create another class representing a 3-d vector.

class C2dVec:
    def __init__(selfij):
        self.icap = i
        self.jcap = j

    def __str__(self):
        return f"{self.icap}i + {self.jcap}j"

class C3dVec(C2dVec):
    def __init__(selfijk):
        super().__init__(ij)
        self.kcap = k
    
    def __str__(self):
        return f"{self.icap}i + {self.jcap}j + {self.kcap}k"
    
    
v2d = C2dVec(13)
v3d = C3dVec(197)
print(v2d)
print(v3d)

Create a class pets from a class Animals and further create class Dog from Pets. Add a method bark to class Dog.

class Animals:
    color = "White"

class Pets(Animals):
    @staticmethod
    def sleep():
        print("Pets are sleeping")


class Dog(Pets):
    
    @staticmethod
    def bark():
        print("Dog is barking Bow Bow")

d = Dog()
print(d.color)
d.sleep()
d.bark()

Create a class Employee and add salary and increment properties to it.

Write a method SalaryAfterIncrement method with a @property decorator with a setter which changes the value of increment based on the salary.

class Employee:
    salary2000
    increments=1.5

    @property
    def salaryAfterIncrements(self):
        return self.salary * self.increments

    @salaryAfterIncrements.setter
    def salaryAfterIncrements(selfsal):
        self.incrementssal / self.salary

e = Employee()
print(e.salaryAfterIncrements)
print(e.increments)
e.salaryAfterIncrements=5000
print(e.salaryAfterIncrements)
print(e.increments)

Write a class complex to represent complex numbers, along with overloaded operators + and * which adds and multiplies them.

class Complex:
    def __init__(selfij):
        self.i =i
        self.j=j
    
    def __add__(self,obj2):
        return Complex(self.i + obj2.i, self.j + obj2.j)
    def __str__(self):
        return f"{self.i} + {self.j}i"
c1=Complex(2,3)
c2=Complex(3,4)
print(c1 + c2)



No comments:

Post a Comment

Featured Post

11g to 12c OSB projects migration points

1. Export 11g OSB code and import in 12c Jdeveloper. Steps to import OSB project in Jdeveloper:   File⇾Import⇾Service Bus Resources⇾ Se...