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.
Create a class pets from a class Animals and further create class Dog from Pets. Add a method bark to class Dog.
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.
Write a class complex to represent complex numbers, along with overloaded operators + and * which adds and multiplies them.
No comments:
Post a Comment