Skip to main content

Posts

Showing posts from January, 2021

Name Mangling in Python With Examples

If you are writing a class in Python and want to follow Encapsulation OOPS concept in Python then how will you stop outside access to the variables as there are no explicit access modifiers like public, private, protected in Python and all the variables are public by default. In Python there is limited support for making class member private and that process is known as name mangling in Python . Table of contents Python name mangling mechanism Name mangling Python example Name mangling with method names How to access name mangled variable Python name mangling with method overriding Python name mangling mechanism In name mangling mechanism any identifier with at least two leading underscores, at most one trailing underscore is textually replaced with _classname__identifier where classname is the current class name. For example if there is a variable __test in the class then it is replaced with _classname__test. Since the name is changed internally by

Polymorphism in Python With Examples

In this post we’ll see the usage of OOPS concept Polymorphism in Python. Table of contents What is Polymorphism Polymorphism in Python Compile time polymorphism (Method Overloading) Runtime polymorphism (Method Overriding) Polymorphism in Python through operator overloading Duck typing and Polymorphism What is Polymorphism Polymorphism is a Greek word where poly means “many” and morph means “change from one form to another”. In object oriented terms it relates to the same object reference taking many forms (assigned different types), a method with the same name having more than one implementations, an operator behaving differently for different operands. Polymorphism in Python In an object oriented language you may see use of Polymorphism in one of the following ways Method overloading, also known as compile time Polymorphism Method overriding, also known as run time Polymorphism Operator overloading In Python you will find support for

Encapsulation in Python With Examples

In this post we’ll see the usage of OOPS concept Encapsulation in Python. Table of contents What is Encapsulation Encapsulation in Python How to control access in Python Using single underscore Using double underscore What is Encapsulation Encapsulation is the process of keeping the data and the code (methods) that manipulates that data together as a unit. Any variable can only be changed through a method in the same class that way data is protected from any intentional or accidental modification by any outside entity. A class is an example of encapsulation as it wraps all the variables and methods defined with in that class. Encapsulation in Python Since class is an example of Encapsulation so defining a class in Python which wraps all the variables and methods is first step towards encapsulation. But the question is how to stop outside access to the variables as there are no explicit access modifiers like public, private, protected in Python and all

isinstance() in Python With Examples

isinstance() function in Python is used to check if the passed object is an instance of the specific class or not. isinstance() is a built-in function in Python. Python isinstance() syntax isinstance(object, classinfo) Returns true if the object (first argument) is an instance of the classinfo (second argument) or any of its subclass. Function returns false if object is not an object of the given type. classinfo can also be a tuple of type objects, in that case isinstance() function returns true of object is an instance of any of the types in a passed tuple. If classinfo is not a type or tuple of types a TypeError exception is raised. Python isinstance() examples 1. Using isinstance() with built-in types i = 7 s = "knocode.com" f = 5.67 print('Is i instance of int:', isinstance(i, int)) print('Is s instance of str:', isinstance(s, str)) print('Is f instance of float:', isinstance(f, float)) print('Is s instance of float:', isinsta

Abstraction in Python With Examples

In this post we’ll see the usage of OOPS concept Abstraction in Python. What is Abstraction Abstraction means hiding the complexity of the implementation and just exposing the essential features to the user. As an example you can take any electronics item where you interact with the product using buttons and switches to turn it on and off or increase and decrease the volume or speed. The real complexity, how that functionality is implemented is hidden from us. In the context of object oriented programming Abstraction means exposing just the end points (methods) and hiding the real implementation from the end user. Abstraction in Python Abstraction in Python is achieved by using abstract classes and interfaces. Abstract class is a class that contains one or more abstract methods. Abstract methods are the methods that don’t contain any implementation, sub classes that inherit from the abstract class should provide implementation for the abstract methods. Abstract class can

super() in Python With Examples

In this tutorial we’ll see what is super() function in Python and how to use it. Python super() function super() is a built-in function in Python which returns a proxy object that can be used to delegate method calls (including call to constructor) to immediate parent class from the child class. Syntax of super() Syntax of super() in Python is as following- super([type[, object-or-type ]]) Suppose you have a child class C inheriting from base class B defined as given below- class C(B): def method(self, arg): super().method(arg) In the method there is a call to method which is defined in the super class using the super() function. Since both of the parameters are optional so this call super().method(arg) is equivalent to super(C, self).method(arg) where both of the parameters are passed. Use of super() 1. Since super() is a proxy object (indirect reference) to the super class so rather than using the super class name directly you can use super() to call super class m

Inheritance in Python With Examples

In this tutorial you’ll learn about OOPS concept inheritance and how to use inheritance in Python. Inheritance concept Inheritance allows us to create a class that acquires, all the properties and methods of another class. The class whose members are inherited is called the Super class. Also known as parent class or base class. The class that inherits from another class is called the Sub class. Also known as child class or derived class. Python inheritance syntax If there is a class called ParentClass defined as- class ParentClass: body of parent class Then a ChildClass that inherits from this ParentClass can be defined as- class ChildClass(ParentClass): body of child class Inheritance Python example In the example there is a class called Person that acts as a base class and another class Employee that inherits from Person class. class Person: def __init__(self, name, age): self.name = name self.age = age def display_person(self): print('In displa

DelayQueue in Java With Examples

DelayQueue in Java is an implementation of BlockingQueue interface and is part of java.util.concurrent package. DelayQueue in Java is an unbounded queue that's where it differs from ArrayBlockingQueue which is a bounded queue. Delayed interface Java DelayQueue can store elements only of type Delayed. There is an interface Delayed in Java which defines the type for these elements. Delayed interface is used to define type of objects that should be acted upon after a given delay. public interface Delayed extends Comparable<Delayed> { long getDelay(TimeUnit unit); } The getDelay(TimeUnit unit) method returns the remaining delay associated with this object, in the given time unit. Since Delayed interface also extends Comparable interface , an implementation of this interface must define a compareTo() method that provides an ordering consistent with its getDelay method. DelayQueue expired elements From DelayQueue in Java an element can only be taken when its

SynchronousQueue in Java With Examples

SynchronousQueue in Java is an implementation of BlockingQueue interface and is part of java.util.concurrent package. SynchronousQueue in Java is different from other BlockingQueue implementations like ArrayBlockingQueue and PriorityBlockingQueue because a synchronous queue does not have any internal capacity , not even a capacity of one. So, each insert operation in SynchronousQueue must wait for a corresponding remove operation by another thread , and vice versa. That is why it is named SynchronousQueue as the hand-off of the element happens synchronously rather than inserting the data that can be retrieved asynchronously. Features of SynchronousQueue in Java SynchronousQueue doesn’t have any internal capacity, not even one. Since there is no capacity each insert operation must wait for a corresponding remove operation by another thread. For example if you insert an element to synchronous queue using put() method the method is blocked until another thread recei

Synchronized Vs ReentrantLock in Java

The traditional way of acquiring a mutual exclusion lock in Java is to use synchronized keyword but Java 5 added new lock implementations like ReentrantLock and ReentrantReadWriteLock which provide extended locking operations capabilities. In this post we'll see the difference between synchronized and ReentrantLock in Java. ReentrantLock Vs synchronized in Java 1- When you use synchronized keyword the implicit lock associated with the object is acquired automatically as soon as the synchronized method or block is entered and the lock is released automatically as soon as the synchronized method or block ends. With ReentrantLock the acquisition and releasing the lock is done using the methods lock() and unlock() . 2- The usage of synchronized is more rigid . All lock acquisition and release should occur in a block-structured way- when multiple locks are acquired they must be released in the opposite order, not doing that may result in a deadlock. All locks must be relea

ReentrantReadWriteLock in Java With Examples

In this post we’ll see the usage of java.util.concurrent.locks.ReadWriteLock interface and its implementing class ReentrantReadWriteLock in Java with examples. Table of contents ReadWriteLock in Java Concurrency Benefits of ReadWriteLock ReentrantReadWriteLock in Java Concurrency Java ReentrantReadWriteLock constructors ReentrantReadWriteLock example in Java ReentrantReadWriteLock Properties ReadWriteLock in Java Concurrency ReadWriteLock as the name itself suggests has a pair of associated locks- One for read-only operations One for writing operations The usage of read lock and write lock is as follows- The read lock may be held simultaneously by multiple reader threads as long as there are no threads with write lock access. The write lock is exclusive. Which means no thread has acquired either read lock or write lock when the thread obtains a write lock. Benefits of ReadWriteLock The traditional way of synchronizing the threads

CountDownLatch Vs CyclicBarrier in Java

Both CountDownLatch and CyclicBarrier are synchronization aids in Java concurrency that facilitate communication among threads. Both of these synchronization aids create a latch or a barrier to make threads wait until a condition is satisfied and then only the threads can make further progress. In this post we’ll see the difference between CountDownLatch and CyclicBarrier in Java. CountDownLatch and CyclicBarrier CyclicBarrier - A synchronization aid that allows a set of threads to all wait for each other to reach a common barrier point. CountDownLatch - A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes. CountDownLatch Vs CyclicBarrier in Java 1- Initialization: A CountDownLatch is initialized with a given count where count denotes the number of times countDown() must be invoked before threads can pass through await(). A CyclicBarrier is initialized with a given number of parties, wh