Author name: Vikram Chiluka

self in Python class

In this article, let us look at what is a self in python class along with some examples to understand the self more clearly.

When we write a class in Python, we need a way to access its attributes and methods. Most languages have a fixed syntax for referring to attributes and methods; C++, for example, uses this for reference.

What is self in Python class?

The self in class is used to represent the instance of the class. In Python, you can access the attributes and methods of the class using this keyword. It binds the attributes with the arguments provided. We use self because Python does not use the ‘@’ syntax to refer to instance attributes. In Python, there are methods that cause the instance to be passed but not received automatically.

Self is always points to the Current Object

self in Python class

Showing the address of self and object

Approach:

  • Create a class say checkSelf.
  • In the constructor, we print the value of self.
  • Create an object for the above class (Here self referes to the this object)
  • Print the id of the above created about using the id() function.
  • The Exit of the Program.

Below is the implementation:

# Here we can observe that the self and rslt_object is referring to the same object
# Create a class say checkSelf
class checkSelf:
  # In the constructor we print the value of self
    def __init__(self):
        print("The Address/Id of self: ", id(self))
        
# Create an object for the above class (Here self referes to the this object)
rslt_object = checkSelf()
# Print the id of the above created about using the id() function
print("The Address/Id of a checkSelf class object: ",id(rslt_object))

Output:

The Address/Id of self: 139973697862096
The Address/Id of a checkSelf class object: 139973697862096

Explanation:

Here we can observe that the self and rslt_object is referring to the
same object. We can see the address of the self and the address of 
the object are the same.

Method #1: Using self to call the methods

Approach:

  • Create a class say Employ
  • Create a init constructor by passing self, employName, employId as arguments to it
  • Initialize the instance variables
  • Create a method say showEmployId which prints the employ id using self
  • Create another method say showEmployName which prints the employ name using self
  • Create a method say showEmployDetails which calls both the methods using self showEmployName(), showEmployId().
  • Create an Instance/object of the above-created Employ class.
  • Call the above method showEmployDetails() using the above employ Object.
  • The Exit of the Program.

Below is the implementation:

# Create a class say Employ
class Employ():

    # Create a init constructor by passing self, employName, employId as arguments to it
    def __init__ (self, employName, employId):
        # Initilaize the instance variables
        self.employName = employName
        self.employId = employId

    # Create a method say showEmployId which prints the employ id using self
    def showEmployId(self):
        print("Employ Id = ", self.employId)
    
    # Create another method say showEmployName which prints the employ name using self
    def showEmployName(self):
        print("Employ Name = ", self.employName)
    
    # Create a method say showEmployDetails which calls both the methods using self
    # showEmployName, showEmployId
    def showEmployDetails(self):
        self.showEmployName()
        self.showEmployId()

# Create an Instance/object of the above created Employ class 
employObj = Employ("John", 2122)

# Call the above method showEmployDetails() using the above employ Object
employObj.showEmployDetails()

Output:

Employ Name = John
Employ Id = 2122

Explanation:

  • Here all the methods of the class have self as the first parameter.
  • The self is used to call the attributes employName and employId.
  • Here, the self is used to call the methods showEmployId() and showEmployName().

NOTE

The term self is not a keyword; rather, it is a Python developer convention.
You can substitute any other word for the first parameter and it will 
still work. However, it is preferable to use self rather than anything 
else because it enhances code readability.

Method #2: Replacing self with some other name

In function, self is a parameter that can be replaced with a different parameter name.

Here we replace self with hello in the above example. Still, it works fine.

Approach:

  • Create a class say Employ
  • Create a init constructor by passing employName, employId as arguments to it using hello instead of self
  • Initilaize the instance variables
  • Create a function say showEmployId which prints the employ id using hello instead of self
  • Create another function say showEmployName which prints the employ name using hello instead of self
  • Create a function say showEmployDetails which calls both the functions showEmployName(), showEmployId() using hello instead of self.
  • Create an Instance/object of the above created Employ class
  • Call the above function showEmployDetails() using the above employ Object.
  • The Exit of the Program.

Below is the implementation:

# Create a class say Employ
class Employ():

    # Create a init constructor by passing employName, employId as 
    # arguments to it using hello instead of self
    def __init__ (hello, employName, employId):
        # Initilaize the instance variables
        hello.employName = employName
        hello.employId = employId

    # Create a function say showEmployId which prints the employ id
    # using hello instead of self
    def showEmployId(hello):
        print("Employ Id = ", hello.employId)
    
    # Create another function say showEmployName which prints the employ name
    # using hello instead of self
    def showEmployName(hello):
        print("Employ Name = ", hello.employName)
    
    # Create a function say showEmployDetails which calls both the functions 
    # showEmployName, showEmployId using hello instead of self
    def showEmployDetails(hello):
        hello.showEmployName()
        hello.showEmployId()

# Create an Instance/object of the above created Employ class 
employObj = Employ("John", 2122)

# Call the above function showEmployDetails() using the above employ Object
employObj.showEmployDetails()

Output:

Employ Name = John
Employ Id = 2122

Method #3: Without Providing self Parameter

The Instance method and constructor, self must be provided as a First parameter. It will result in an error if you do not provide it.

# Here we can observe that the self is not passed as the first parameter
# in the init constructor. Hence it throws an error

# Create a class say checkwithoutSelf
class checkwithoutSelf:
  # In the init constructor we don't pass the self 
    def __init__():
        print("hello this is python programs")

# Create an object for the above class 
rslt_object = checkwithoutSelf()
print("Welcome")

Output:

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-43-394e0a56a3d8> in <module>
9 
10 # Create an object for the above class
---> 11 rslt_object = checkwithoutSelf()
12 print("Welcome")

TypeError: __init__() takes 0 positional arguments but 1 was given

 

self in Python class Read More »

Avoiding quotes while printing strings in Python

In Python, there are several methods for removing quotes from a string. You may need to remove all quotes or only those that surround a string. You may need to remove single or double quotes as well.

If we print a given list of strings as is, we must use quotes and properly fill in a pair of matching quotes. We can avoid using quotes in print statements.

In this article let us look at how to remove these quotes on strings using the below-given methods:

  • Using join() Function
  • Using the print() & sep keyword

Avoiding quotes while printing strings in Python

Method #1: Using join() function (Static Input)

Join(sequence) joins elements and returns the combined string. Every element of the sequence is combined using the join methods.
A sequence is passed as an argument to the join method. The sequence is written as a single argument: you must surround it with brackets.

You can pass a variable containing the sequence as an argument if you want. This improves readability.

The join() method joins all items in an iterable into a single string.

As the separator, a string must be specified.

Syntax:

string.join(iterable)

Parameters:

iterable: This is required. Any iterable object whose returned values are all strings.

Approach:

  • Give the list of strings as static input and store it in a variable.
  • Print the given list
  • Remove the quotes for the strings in a given list using the join() function by passing the given list as an argument to it by specifying the separator as comma(,) delimiter.
  • The Exit of the Program.

Below is the implementation:

# Give the list of strings as static input and store it in a variable.
gvn_lst = ['Hello', 'this', 'is', 'PythonPrograms']

# Print the given list
print ("The given list = ", gvn_lst)

# Remove the quotes for the strings in a given list using the join() function
# by passing the given list as an argument to it.
print ("The given list after removing quotes on strings: ")
print (', '.join(gvn_lst))

Output:

The given list = ['Hello', 'this', 'is', 'PythonPrograms']
The given list after removing quotes on strings: 
Hello, this, is, PythonPrograms

Method #2: Using join() Function (User Input)

Approach:

  • Give the list of strings as user input using the list(),map(),split(),str functions and store it in a variable.
  • Print the given list.
  • Remove the quotes for the strings in a given list using the join() function by passing the given list as an argument to it by specifying the separator as comma(,) delimiter.
  • The Exit of the Program.

Below is the implementation:

# Give the list of strings as user input using the list(),map(),split(),str
# functions and store it in a variable.
gvn_lst = list(map(str, input(
   'Enter some random List Elements separated by spaces = ').split()))

# Print the given list
print ("The given list = ", gvn_lst)

# Remove the quotes for the strings in a given list using the join() function
# by passing the given list as an argument to it.
print ("The given list after removing quotes on strings: ")
print (', '.join(gvn_lst))

Output:

Enter some random List Elements separated by spaces = Welcome to pythonprograms
The given list = ['Welcome', 'to', 'pythonprograms']
The given list after removing quotes on strings: 
Welcome, to, pythonprograms

Method #3: Using the print() & sep keyword (Static Input)

Approach:

  • Give the list of strings as static input and store it in a variable.
  • Print the given list
  • Remove the quotes for the strings in a given list by passing the separator as comma(,) as delimiter and print the result.
  • The Exit of the Program.

Below is the implementation:

# Give the list of strings as static input and store it in a variable.
gvn_lst = ['Hello', 'this', 'is', 'PythonPrograms']

# Print the given list
print ("The given list = ", gvn_lst)

# Remove the quotes for the strings in a given list by passing the
# separator as comma(,) as delimiter and print the result 
print ("The given list after removing quotes on strings: ")
print(*gvn_lst, sep =', ')

Output:

The given list = ['Hello', 'this', 'is', 'PythonPrograms']
The given list after removing quotes on strings: 
Hello, this, is, PythonPrograms

Method #4: Using the print() & sep keyword (User Input)

Approach:

  • Give the list of strings as user input using the list(),map(),split(),str functions and store it in a variable.
  • Print the given list.
  • Remove the quotes for the strings in a given list by passing the separator as comma(,) as delimiter and print the result.
  • The Exit of the Program.

Below is the implementation:

# Give the list of strings as user input using the list(),map(),split(),str
# functions and store it in a variable.
gvn_lst = list(map(str, input(
   'Enter some random List Elements separated by spaces = ').split()))

# Print the given list
print ("The given list = ", gvn_lst)

# Remove the quotes for the strings in a given list by passing the
# separator as comma(,) as delimiter and print the result 
print ("The given list after removing quotes on strings: ")
print(*gvn_lst, sep =', ')

Output:

Enter some random List Elements separated by spaces = Welcome to pythonprograms
The given list = ['Welcome', 'to', 'pythonprograms']
The given list after removing quotes on strings: 
Welcome, to, pythonprograms

Avoiding quotes while printing strings in Python Read More »

Method Overriding in Python

In this tutorial, let us look at what is method overriding in python along with examples, and its key features.

Method overriding in Python:

Method overriding is a form of Run time polymorphism. The child class provides the specific implementation of the method that is already provided by the parent class. It is used to change the behavior of existing methods, and method overriding requires at least two classes. In method overriding, inheritance is always required because it occurs between methods from the parent class (superclass) and the child class (child class).

parent class: The class that is being inherited is known as the Parent or Superclass.

child class: The class that inherits the parent class’s properties and methods is known as the Child or Subclass.

Features of Method overriding

  • The concept of method overriding is derived from object-oriented programming(OOPS).
  • It allows us to change the implementation of a function in the child class that is defined in the parent class.
  • It is a part of the inheritance concept.
  • Method overriding avoids code duplication while also improving the code by adding some extra properties.

Method overriding Prerequisites 

In Python, there are some prerequisites for method overriding. They are:

  • Method overriding is not possible within a class. As a result, we must derive a child class from a parent class. So, inheritance is required.
  • The method’s name must be the same as in the parent class.
  • The method’s parameters must be the same as those in the parent class.

Approach:

  • Create a parent class say FirstClass
  • Inside the parent class, create a function say display1().
  • Create another function say display2.
  • Create a child class say SecondClass() which inherits properties from the parent class, FirstClass().
  • Create a function with the same name say display1 as in the parent which modifies or overrides the text when it is called.
  • Create an object for the child class say SecondClass() and store it in a variable.
  • Call the display1() function of the SecondClass() which overrides the display1() function of the FirstClass.
  • The Exit of the Program.

Below is the implementation:

# Create a parent class say FirstClass
class FirstClass:
    
    # Create a function say display1
    def display1(self):
        print('display_1 of the FirstClass')
    
    # Create another function say display2
    def display2(self):
        print('display_2 of the FirstClass')
    
# Create a child class say SecondClass which inherits properties from parent class, FirstClass
class SecondClass(FirstClass):
    
    # Create a function with the same name say display1 as in the parent parent
    # which modifies or overrides the text when it is called
    def display1(self):
        print('Overriding display1() class of FirstClass by the SecondClass')
        
    def display3(self):
        print('display_3 of the SecondClass')
        

# Create an object for the child class say SecondClass() and store it in a variable
secondClass_object = SecondClass()
    
# Call the display1() fuction of the SecondClass() which overrides the 
# display1() function of the FirstClass
secondClass_object.display1()

Output:

Overriding display1() class of FirstClass by the SecondClass

Method overriding with Multiple Inheritance

Multiple inheritance occurs when a class is derived from one or more parent(base) classes, inheriting all of its properties.

Overriding in Multiple Inheritance occurs when a child class provides its own implementation of methods/attributes while inheriting them from its parent/parents.

Approach:

  • Create a parent class say Vehicle.
  • Inside the class, create a function say vehicletype.
  • Create another function say brand.
  • Create a class say Twowheeler which inherits properties from the parent class Vehicle.
  • Create another class say Threewheeler which inherits properties from the parent class Vehicle.
  • Create another child class say Fourwheeler which inherits properties from the above both the child classes Twowheeler and Threewheeler.
  • Create an object for the last child class Fourwheeler.
  • Call the vehicletype() function from the Vehicle class and print the result.
  • Call the brand() function from the Vehicle class and print the result.
  • The Exit of the Program.

Below is the implementation:

# Create a parent class say Vehicle
class Vehicle:
    # Inside the class, create a function say vehicletype
    def vehicletype(self):
        print("This gives the type of vehicle")
    # create another function say brand
    def brand(self):
        print("It gives the brand of vehicle")

# Create class say Twowheeler which inherits properties 
# from the parent class Vehicle
class Twowheeler (Vehicle): 
    def vehicletype(self):
        print("Bike is a type of Twowheeler")

# Create another class say Threewheeler which inherits properties 
# from the parent class Vehicle
class Threewheeler (Vehicle): 
    def vehicletype(self):
        print("Auto is a type of Threewheeler")

# Create another child class say Fourwheeler which inherits properties 
# from the above both the child classes Twowheeler and Threewheeler     
class Fourwheeler (Twowheeler, Threewheeler): 
    def vehicletype(self):
        print("Car is a type of Fourwheeler")
        
# Create an object for the last child class Fourwheeler
obj = Fourwheeler() 

# call the vehicletype() function from the Vehicle class and print the result
obj.vehicletype() 
# call the brand() function from the Vehicle class and print the result
obj.brand()

Output:

Car is a type of Fourwheeler
It gives the brand of vehicle

Method overriding with Multi-level Inheritance

Features from both the base and derived classes are inherited into the new derived class in multilevel inheritance. This is comparable to a child and grandfather relationship.

Approach:

  • Create a parent class say Vehicle.
  • Inside the class, create a function say vehicletype.
  • Create another function say brand.
  • Create a child class say Twowheeler which inherits properties from the parent class Vehicle.
  • Create another child class say Threewheeler which inherits properties from the first child class Twowheeler.
  • Create an object for the last child class Threewheeler.
  • Call the vehicletype() function from the Vehicle class and print the result.
  • Call the brand() function from the Vehicle class and print the result.
  • The Exit of the Program.

Below is the implementation:

# Create a parent class say Vehicle
class Vehicle:

    # Inside the class, create a function say vehicletype
    def vehicletype(self):
        print("This gives the type of vehicle")
    # create another function say brand
    def brand(self):
        print("It gives the brand of vehicle")

# Create a child class say Twowheeler which inherits properties 
# from the parent class Vehicle
class Twowheeler(Vehicle): 
    def vehicletype(self):
        print("Bike is a type of Twowheeler")

# Create another child class say Threewheeler which inherits properties 
# from the first child class Twowheeler
class Threewheeler(Twowheeler): 
    def vehicletype(self):
        print("Auto is a type of Threewheeler")

# Create an object for the last child class Threewheeler
obj = Threewheeler() 

# call the vehicletype() function from the Vehicle class and print the result
obj.vehicletype() 
# call the brand() function from the Vehicle class and print the result
obj.brand() 

Output:

Auto is a type of Threewheeler
It gives the brand of vehicle

 

Method Overriding in Python Read More »

Method Overloading in Python

In this article, let us look at Method Overloading in Python.

Method Overloading:

Method Overloading is a form of Compile time polymorphism. In the case of method overloading, multiple methods belonging to the same class can have the same method name but different number of signatures/ arguments.

Method overloading can be used to add more to the behavior of the concerned methods. A user will not require more than one class to implement it.

NOTE:

Note that Python does not support method overloading. A user may overload 
all of the methods, but they will only be able to use the
lastest defined method.

Example

Approach:

  • Create a class say MethodOverloading
  • Inside the class, create a function say multiply which accepts two numbers as arguments and prints the multiplication result of those two numbers.
  • Create another function with the same name say multiply which accepts three numbers as arguments and prints the multiplication result of those three numbers.
  • Create an object for the above MethodOverloading() class.
  • Pass two numbers as arguments to the multiply() function and apply it on the above object and print the result.
  • Pass three numbers as arguments to the multiply() function and apply it on the above object and print the result.
  • The Exit of the Program.

Below is the implementation:

# Create a class say MethodOverloading
class MethodOverloading:
   # Create a function say multiply which accepts two numbers as arguments 
   # and prints the multiplication result of those two numbers
   def multiply(self, x, y):
       print(x*y)
   # Create another function with the same name say multiply which accepts three 
   # numbers as arguments and prints the multiplication result of those three numbers
   def multiply(self, x, y, z):
       print(x*y*z)

# Create an object for the above MethodOverloading() class      
obj =MethodOverloading()
# Pass two numbers as arguments to the multiply() function and apply it 
# on the above object and print the result
print(obj.multiply(2, 3))
# Pass three numbers as arguments to the multiply() function and apply it 
# on the above object and print the result
print(obj.multiply(2, 3, 4))

Output:

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-7d5007590dae> in <module>
14 # Pass two numbers as arguments to the multiply() function and apply it
15 # on the above object and print the result
---> 16 print(obj.multiply(2, 3))
17 # Pass three numbers as arguments to the multiply() function and apply it
18 # on the above object and print the result

TypeError: multiply() missing 1 required positional argument: 'z'

Explanation:

Python does not support method overloading because Python always uses the last defined method. We can still overload methods in Python, but it’s pointless. However, method overloading can be implemented in Java, C++, and other languages in the manner described above.

Another way to perform method overloading in Python is as follows:

Approach:

  • Create a class say MethodOverloading.
  • Create a function say multiply which accepts two numbers as arguments and prints the multiplication result of those two numbers based on conditions.
  • Check if both the numbers are not equal to None using the if conditional statement, and operator.
  • If it is true then return the multiplication of both the numbers.
  • Else if Check only the first number passed is not None using the elif conditional statement.
  • If it is true then return only the first number.
  • Else return 0.
  • Create an object for the above MethodOverloading() class.
  • Call the above multiply() function without passing any arguments and print the result.
  • Call the above multiply() function by passing only one number as an argument and print the result.
  • Call the above multiply() function by passing two numbers as arguments and print the result.
  • The Exit of the Program.

Below is the implementation:

# Create a class say MethodOverloading
class MethodOverloading:
    # Create a function say multiply which accepts two numbers as arguments 
    # and prints the multiplication result of those two numbers based on conditions
    def multiply(self, a = None, b = None):
        # Check if both the numbers are not equal to None using the if conditional 
        # statement, and operator
        if a!= None and b!= None:
            # If it is true then return the multiplication of both the numbers
            return  a*b
        # else if Check only the first number passed is not None using the elif conditional statement
        elif a!= None:
            # If it is true then return only the first number
            return a
        else:
            # Else return 0
            return 0

# Create an object for the above MethodOverloading() class  
class_object = MethodOverloading()

# Call the above multiply() function without passing any arguments and print the result
print("Result = ", class_object.multiply())
# Call the above multiply() function by passing only one number as an argument and print the result
print("Result = ", class_object.multiply(3))
# Call the above multiply() function by passing two numbers as arguments and print the result
print("Result = ", class_object.multiply(4, 5))

Output:

Result = 0
Result = 3
Result = 20

Advantages of Method overloading

  • Reduces complexities and improves code quality
  • Method overloading is also used for reusability and easy accessibility.
  • Using Python method overloading, you can make multiple methods appear logically as a single method. For example, we have only one method – get area – that can be used to calculate the area of different shapes depending on the type of input given to the function while still presenting itself logically as one method. This improves the readability of the code, making it easier for the programmer to write code and increasing the programmer’s efficiency.
  • We can also keep backward compatibility by using method overloading. What does this imply? If we have a method that performs complex calculations, we could add a new requirement to it that allows it to perform the same complex calculation with minor changes. If we add a new parameter (optional parameter), its presence will be used to perform calculations in either the old or new way.

Method overloading In Brief

  • Same method name but different number of arguments.
  • Inheritance is not required(optional).
  • It is an example of compile time polymorphism.
  • It is performed between methods within the class.
  • Overloading can be done within a class
  • Method Overloading is used to add more to the behavior of methods.
  • Static methods can be overloaded here.
  • It is related with Polymorphism concept of OOPs.

Method overloading allows you to call the same method in multiple ways. All of the methods will have the same name, but there may be three differences:

  • The number of parameters could vary.
  • The data type of arguments
  • The order of the parameters

Method Overloading in Python Read More »

Difference between Method Overloading and Method Overriding in Python

In this article, let us look at Method Overloading and Method Overriding in python and what are the differences between Method Overloading and Method Overriding.

Method Overloading:

Method Overloading is a form of Compile time polymorphism. In the case of method overloading, multiple methods belonging to the same class can have the same method name but different signatures.

Method overloading can be used to add more to the behavior of the concerned methods. A user will not require more than one class to implement it.

NOTE:

Note that Python does not support method overloading. A user may overload 
all of the methods, but they will only be able to use the
lastest defined method.

Example

Approach:

  • Create a class say MethodOverloading
  • Create a function say multiply which accepts two numbers as arguments and prints the multiplication result of those two numbers.
  • Create another function with the same name say multiply which accepts three numbers as arguments and prints the multiplication result of those three numbers.
  • Create an object for the above MethodOverloading() class
  • Pass two numbers as arguments to the multiply() function and apply it on the above object and print the result.
  • Pass three numbers as arguments to the multiply() function and apply it on the above object and print the result.
  • The Exit of the Program.

Below is the implementation:

# Create a class say MethodOverloading
class MethodOverloading:
   # Create a function say multiply which accepts two numbers as arguments 
   # and prints the multiplication result of those two numbers
   def multiply(self, x, y):
       print(x*y)
   # Create another function with the same name say multiply which accepts three 
   # numbers as arguments and prints the multiplication result of those three numbers
   def multiply(self, x, y, z):
       print(x*y*z)

# Create an object for the above MethodOverloading() class      
obj =MethodOverloading()
# Pass two numbers as arguments to the multiply() function and apply it 
# on the above object and print the result
print(obj.multiply(2, 3))
# Pass three numbers as arguments to the multiply() function and apply it 
# on the above object and print the result
print(obj.multiply(2, 3, 4))

Output:

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-7d5007590dae> in <module>
14 # Pass two numbers as arguments to the multiply() function and apply it
15 # on the above object and print the result
---> 16 print(obj.multiply(2, 3))
17 # Pass three numbers as arguments to the multiply() function and apply it
18 # on the above object and print the result

TypeError: multiply() missing 1 required positional argument: 'z'

Explanation:

Python does not support method overloading because Python always uses the last defined method. We can still overload methods in Python, but it’s pointless. However, method overloading can be implemented in Java, C++, and other languages in the manner described above.

Another way to perform method overloading in Python is as follows:

# Create a class say MethodOverloading
class MethodOverloading:
    # Create a function say multiply which accepts two numbers as arguments 
    # and prints the multiplication result of those two numbers based on conditions
    def multiply(self, a = None, b = None):
        # Check if both the numbers are not equal to None using the if conditional 
        # statement, and operator
        if a!= None and b!= None:
            # If it is true then return the multiplication of both the numbers
            return  a*b
        # else if Check only the first number passed is not None using the elif conditional statement
        elif a!= None:
            # If it is true then return only the first number
            return a
        else:
            # Else return 0
            return 0

# Create an object for the above MethodOverloading() class  
class_object = MethodOverloading()

# Call the above multiply() function without passing any arguments and print the result
print("Result = ", class_object.multiply())
# Call the above multiply() function by passing only one number as an argument and print the result
print("Result = ", class_object.multiply(3))
# Call the above multiply() function by passing two numbers as arguments and print the result
print("Result = ", class_object.multiply(4, 5))

Output:

Result = 0
Result = 3
Result = 20

Method Overriding

Method overriding is a form of Run time polymorphism. The child class provides the specific implementation of the method that is already provided by the parent class. It is used to change the behavior of existing methods, and method overriding requires at least two classes. In method overriding, inheritance is always required because it occurs between methods from the parent class (superclass) and the child class (child class).

Approach:

  • Create a parent class say FirstClass
  • Inside the parent class, create a function say display1().
  • Create another function say display2.
  • Create a child class say SecondClass() which inherits properties from the parent class, FirstClass().
  • Create a function with the same name say display1 as in the parent which modifies or overrides the text when it is called.
  • Create an object for the child class say SecondClass() and store it in a variable.
  • Call the display1() function of the SecondClass() which overrides the display1() function of the FirstClass.
  • The Exit of the Program.

Below is the implementation:

# Create a parent class say FirstClass
class FirstClass:
    
    # Create a function say display1
    def display1(self):
        print('display_1 of the FirstClass')
    
    # Create another function say display2
    def display2(self):
        print('display_2 of the FirstClass')
    
# Create a child class say SecondClass which inherits properties from parent class, FirstClass
class SecondClass(FirstClass):
    
    # Create a function with the same name say display1 as in the parent parent
    # which modifies or overrides the text when it is called
    def display1(self):
        print('Overriding display1() class of FirstClass by the SecondClass')
        
    def display3(self):
        print('display_3 of the SecondClass')
        

# Create an object for the child class say SecondClass() and store it in a variable
secondClass_object = SecondClass()
    
# Call the display1() fuction of the SecondClass() which overrides the 
# display1() function of the FirstClass
secondClass_object.display1()

Output:

Overriding display1() class of FirstClass by the SecondClass

Difference between Method Overloading and Method Overriding in Python

            Method Overloading               Method Overriding
Same method name but the different number of argumentsSame method name and the same number of arguments
Inheritance is not required(optional).Inheritance is not required(optional).
It is an example of compile time polymorphism.It is an example of run-time polymorphism.
It is performed between methods within the class.Method overriding occurs between parent and child class methods.
Overloading can be done within a classA minimum of two classes are required for overriding  
Overloading is used to add more to the behavior of methods.Overriding is used to change the behavior of existing methods.
Static methods can be overloaded hereStatic methods cannot be overloaded here
It is related with PolymorphismIt is related with Inheritance.

Difference between Method Overloading and Method Overriding in Python Read More »

Python slice() function

In this article we are going to discuss about the slice() function in python with examples.

slice() function in Python:

Based on the specified range, the slice() method returns a portion of an iterable as an object of the slice class. It works with string, list, tuple, set, bytes, or range objects, as well as custom class objects that implement the sequence methods, __getitem__() and __len__().

Syntax:

slice(stop)
slice(start, stop, step)

Parameters

  • start: This is optional. The index at which the iterable’s slicing starts. None is the default value
  • stop: This is the ending index of slicing.
  • step: This is optional. It is the number of steps to jump/increment.

Python slice() function

Method #1: Using slice() function on Strings

Approach:

  • Give the string as static input and store it in a variable.
  • Slice the given string using the slice() function by passing start, and stop values as arguments to it (default step size is 1).
  • Here it returns the string in the index range of 2 to 9(excluding the last index).
  • Print the result string after slicing.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = 'Hello this is PythonPrograms'
# Slice the given string using the slice() function by passing start, stop 
# values as arguements to it(default stepsize is 1)
# Here it returns the string in the index range 2 to 9(excluding the last index)
# NOTE: It also considers the space as an index value
sliceObj = slice(2, 10)

# Print the result string after slicing
print("The result string after slicing = ", gvn_str[sliceObj])

Output:

The result string after slicing = llo this

NOTE:

 It also considers the space as an index value

If only one parameter is specified, start and step are assumed to be None.

# Give the string as static input and store it in a variable.
gvn_str = 'Hello this is PythonPrograms'

# Pass only the stop value as an argument to the slice() function 
# to get the portion of the string in the given range
# Here start and step values are considered 0, 1 respectively and 
# we get a string in the index range 0 to 9
sliceObject_1 = slice(10)

# Slice the given string by passing the start, stop, step values as arguments
# slice() function and  store it in a variable.
# Here it returns the string from index 1 to 13(excluding last index) with the step value 2 
sliceObject_2 = slice(1, 14, 2)
 
# Print the  result string 1 after slicing
print("The result string in the index range 0 to 9: ", gvn_str[sliceObject_1])
# Print the  result string 1 after slicing
print("The result string in the index range 1 to 13 with step=2: ", gvn_str[sliceObject_2])

Output:

The result string in the index range 0 to 9: Hello this
The result string in the index range 1 to 13 with step=2: el hsi

Method #2: Using slice() function on Lists

Approach:

  • Give the list as static input and store it in a variable.
  • Pass start, and stop as arguments to the slice() function to get the part of the list (default stepsize is 1) and store it in a variable.
  • Here it returns the list elements in the index range 2 to 6(excluding the last index)
  • Pass only the stop value as an argument to the slice() function to get the portion of the list in the given range.
  • Here start and step values are considered 0, 1 respectively by default and
    we get a list of elements in the index range of 0 to 4
  • Slice the given list by passing the start, stop, and step values as arguments to the slice() function and storing it in a variable.
  • Here it returns list elements from index 1 to 7(excluding the last index) with the step value 2
  • Print the result list elements in the index range 2 to 6
  • Print the result list elements in the index range 0 to 4
  • Print the result list elements in the index range 1 to 7 with step=2.
  • The Exit of the Program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gvn_list = [1, 3, 6, 8, 9, 4, 10, 14, 18]


# Pass start, stop as arguments to the slice() function to get the part of the list
# (default stepsize is 1) and store it in a variable.
# Here it returns the list elements in the index range 2 to 6(excluding the last index)
sliceObject_1 = slice(2, 7)

# Pass only the stop value as an argument to the slice() function 
# to get the portion of the list in the given range
# Here start and step values are considered 0, 1 respectively bu default and 
# we get a list elements in the index range 0 to 4
sliceObject_2 = slice(5)

# Slice the given list by passing the start, stop, step values as arguments
# to the slice() function and store it in a variable.
# Here it returnslist elements from index 1 to 7(excluding last index) with the step value 2 
sliceObject_3 = slice(1, 8, 2)
 
# Print the result list elements in the index range 2 to 6
print("The result list elements in the index range 2 to 6: ", gvn_list[sliceObject_1]) 
# Print the result list elements in the index range 0 to 4
print("The result list elements in the index range 0 to 4: ", gvn_list[sliceObject_2])
# Print the result list elements in the index range 1 to 7 with step=2
print("The result list elements in the index range 1 to 7 with step=2: ", gvn_list[sliceObject_3])

Output:

The result list elements in the index range 2 to 6: [6, 8, 9, 4, 10]
The result list elements in the index range 0 to 4: [1, 3, 6, 8, 9]
The result list elements in the index range 1 to 7 with step=2: [3, 8, 4, 14]

Method #3: Using slice() function on Tuples

# Give the list as static input and store it in a variable.
gvn_tuple = (1, 3, 6, 8, 9, 4, 10, 14, 18)


# Pass start, stop as arguments to the slice() function to get the part of the 
# given tuple(default stepsize is 1) and store it in a variable.
# Here it returns the tuple elements in the index range 2 to 6(excluding the last index)
sliceObject_1 = slice(2, 7)

# Pass only the stop value as an argument to the slice() function 
# to get the portion of the tuple in the given range
# Here start and step values are considered 0, 1 respectively by default and 
# we get a tuple elements in the index range 0 to 4
sliceObject_2 = slice(5)

# Slice the given tuple by passing the start, stop, step values as arguments
# to the slice() function and store it in a variable.
# Here it returns the tuple elements from index 1 to 7(excluding last index)
# with the step value 2 
sliceObject_3 = slice(1, 8, 2)
 
# Print the result tuple elements in the index range 2 to 6
print("The result tuple elements in the index range 2 to 6: ", gvn_tuple[sliceObject_1]) 
# Print the result tuple elements in the index range 0 to 4
print("The result tuple elements in the index range 0 to 4: ", gvn_tuple[sliceObject_2])
# Print the result tuple elements in the index range 1 to 7 with step=2
print("The result tuple elements in the index range 1 to 7 with step=2: ", gvn_tuple[sliceObject_3])

Output:

The result tuple elements in the index range 2 to 6: (6, 8, 9, 4, 10)
The result tuple elements in the index range 0 to 4: (1, 3, 6, 8, 9)
The result tuple elements in the index range 1 to 7 with step=2: (3, 8, 4, 14)

Method #4: Using Negative Indexing

Python supports “indexing from the end,” or negative indexing.
This means that the last value in a sequence has a -1 index, the second last has a -2 index, etc.
If you wish to select values from the end (right side) of an iterable, you can use negative indexing.

Negative sequence indexes in Python represent positions from the array’s end. The slice() function can return negative values. In that case, the iteration will be performed backward, from end to start.

# Slicing the given list using negative indexing
# Here -1 represents the last element of the list 
gvn_list = [1, 3, 6, 8, 9, 4, 10, 14, 18]
sliceObject = slice(-1, -4, -1)
print("Slicing the given list = ", gvn_list[sliceObject])

# Slicing the given string using negative indexing
gvn_string = "Pythonprograms"
sliceObject = slice(-1)
print("Slicing the given string = ", gvn_string[sliceObject])

# Slicing the given tuple using negative indexing
gvn_tuple = (1, 3, 6, 8, 9, 4, 10)
sliceObject = slice(-1, -6, -2)
print("Slicing the given tuple = ", gvn_tuple[sliceObject])

Output:

Slicing the given list = [18, 14, 10]
Slicing the given string = Pythonprogram
Slicing the given tuple = (10, 9, 6)

 

 

Python slice() function Read More »

Python OOPs Concepts

Object-oriented Programming (OOPs) is a programming paradigm in Python that employs objects and classes. It aims to incorporate real-world entities such as inheritance, polymorphisms, encapsulation, and so on into programming. The main idea behind OOPs is to bind the data and the functions that work on it as a single unit so that no other part of the code can access it.

The object is associated with real-world entities such as a book, a house, a pencil, and so on. The oops concept is concerned with writing reusable code. It is a common technique for solving problems by creating objects.

Fundamental Concepts of Object-oriented Programming (OOPs)

  • Class
  • Object
  • Method
  • Inheritance
  • Polymorphism
  • Data Abstraction
  • Encapsulation

Python OOPs Concepts

Class

A class is a collection of objects, or a blueprint of objects that defines the common attributes and methods. The question now is, how do you do that?

It logically groups the data in such a way that code reusability is made simple. Consider an office going ’employee’ as a class and all the attributes related to it like ’empName,’ ’empAge,’ ’empSalary,’ and ’empId’ as Python objects.

Syntax:

class ClassName: 
<statement-1> 
.

.
<statement-N>

Example: Create an empty class

# Create an empty class say Btechgeeks
class Pythonprograms:
    pass

Object

The object is an entity that has a state and behavior. The object is a stateful entity with behaviour. It could be any real-world object, such as a mouse, keyboard, chair, table, pen, etc.

In Python, everything is an object, and almost everything has attributes and methods. All functions have a built-in attribute __doc__, which returns the docstring defined in the function source code.

When we define a class, we must create an object to allocate memory.

An object is made up of:

  • state: The state is represented by the attributes of an object. It also reflects an object’s properties.
  • behavior: The behavior is represented by the methods of an object. It also represents an object’s response to other objects.
  • Identity: It gives an object a unique name and allows it to interact with other objects.

Let us consider the class dog to better understand its state, behaviour, and identity:

  • The identity can be thought of as the dog’s name.
  • The breed, age, and color of the dog are examples of state or attributes.
  • The behavior can be used to determine whether the dog is eating or sleeping.

Example

# create a class say Employ
class Employ:  
    def __init__(self, empName, empId):  
        self.empName = empName  
        self.empId = empId  
    def displayEmpDetails(self):  
        print(self.empName,self.empId)  

# calling the Employ class by passing the empName, empId as arguments
emp_object = Employ("Nick", 2122)  
# Display the employ details by calling the displayEmpDetails()
# method using the emp_object
emp_object.displayEmpDetails()  

Output:

Nick 2122

Method

A method is a function that is linked to an object. A method in Python is not unique to class instances. Methods can exist on any object type.

__init__ method:

The __init__ method is similar to C++ and Java constructors. It is executed whenever a class object is instantiated. The method is useful for performing any initialization on your object.

Inheritance

The most important aspect of object-oriented programming is inheritance, which simulates the real-world concept of inheritance. It specifies that the child object inherits/acquires all of the parent object’s properties and behaviors.

We can use inheritance to create a class that inherits all of the properties and behavior of another class. The new class is referred to as a derived class or child class, while the class whose properties are acquired is referred to as a base class or parent class.

It ensures that the code can be reused.

There are 4 types of inheritance in python. They are:

1)Single Inheritance:

A derived class can inherit characteristics from a single-parent class through single-level inheritance.

# Create a parent calss say Employ()
class Employ():
  def __init__(self, empName, empId):  
    self.empName = empName
    self.empId = empId

# Create a child calss say EmployChildClass()
class EmployChildClass(Employ):
  def __init__(self, empName, empId, empRole):
    self.empName = empName
    self.empId = empId
    self.empRole = empRole

# Calling the above Employ parent class by passing empName, empId, empRole
# as arguments to it
emp_object = Employ('Isha', 2122)

# Printing the empId using the emp_object
print(emp_object.empId)

Output:

2122

2)Multi-level Inheritance:

Multi-level inheritance allows a derived class to inherit properties from an immediate parent class, which in turn inherits properties from his parent class.

# Create a parent calss say Employ()
class Employ():
  def __init__(self, empName, empId):  
    self.empName = empName
    self.empId = empId

# Create a first child class say EmployChildClass_1() 
# inheriting properties from parent class Employ
class EmployChildClass_1(Employ):
  def __init__(self, empName, empId):  
    self.empName = empName
    self.empId = empId

# Create a second child class say EmployChildClass_2() 
# inheriting properties from first child class EmployChildClass_1 
class EmployChildClass_2(EmployChildClass_1):
   def __init__(self, empName, empId):  
    self.empName = empName
    self.empId = empId

employ_1 = Employ('Nick', 2122)
employ_2 = EmployChildClass_1('John', 2123)
 
print(employ_1.empId)
print(employ_2.empId)

Output:

2122
2123

3)Hierarchical Inheritance:

More than one derived class can inherit properties from a parent class using hierarchical-level inheritance.

# Create a parent calss say Employ()
class Employ():
  def __init__(self, empName, empId):  
    self.empName = empName
    self.empId = empId

# Create a first child class say EmployChildClass_1() 
# inheriting properties from parent class Employ
class EmployChildClass_1(Employ):
  def __init__(self, empName, empId):  
    self.empName = empName
    self.empId = empId

# Create a second child class say EmployChildClass_2() 
# inheriting properties from parent class Employ
class EmployChildClass_2(Employ):
   def __init__(self, empName, empId):  
    self.empName = empName
    self.empId = empId

employ_1 = Employ('Nick', 2122)
employ_2 = Employ('John', 2123)
 
print(employ_1.empId)
print(employ_2.empId)

Output:

2122
2123

4)Multiple Inheritance:

Multiple inheritance allows a single derived class to inherit properties from multiple base classes.

# Create a parent class say Employ_1()
class Employ_1():
    def __init__(self, empName, empId):  
      self.empName = empName
      self.empId = empId

# Create another parent class say Employ_2()
class Employ_2():
    def __init__(self, empName, empId, empRole):
      self.empName = empName
      self.empId = empId
      self.empRole = empRole
 
# Create a child class say EmployChildClass() 
# inheriting properties from both the parent classes
class EmployChildClass(Employ_1, Employ_2):
    def __init__(self, empName, empId, empRole):
      self.empName = empName
      self.empId = empId
      self.empRole = empRole

employ1 = Employ_1('Nick', 2122)
employ2 = Employ_2('John', 2123, 'Analyst')
 
print(employ1.empId)
print(employ2.empRole)

Output:

2122
Analyst

Polymorphism

Polymorphism is derived from the Greek words poly (many) and morphism (forms). That is, the same function name can be used for many types. This makes programming more intuitive and simple.

Polymorphism means that the same task can be performed in different ways. For example, suppose you have a class animal and all of the animals speak. But they communicate in different ways. In this case, the “speak” behavior is polymorphic and varies depending on the animal. So, while the abstract concept of “animal” does not actually “speak,” specific animals (such as dogs and cats) have a concrete implementation of the action “speak.”

A child class inherits all of the parent class’s methods. In other cases, however, the method inherited from the parent class does not fully fit into the child class. In such circumstances, you must re-implement the method in the child class.

Example

# Create a parent class say Vehicle
class Vehicle:

    def introduction(self):
        print("Vehicles have different models")

    def categories(self):
        print("some are two-wheelers and some four-wheelers etc")

# Create a child class say Car() inheriting properties the parent class Vehicle
class Car(Vehicle):

    def categories(self):
        print("Car is a four-wheeler")

# Create another child class say Bike() inheriting properties the parent class Vehicle
class Bike(Vehicle):

    def categories(self):
        print("Bike is a two-wheeler")

Vehicle_object = Vehicle()
Car_object = Car()
Bike_object = Bike()

Vehicle_object.introduction()
Vehicle_object.categories()
print()
Car_object.introduction()
Car_object.categories()
print()
Bike_object.introduction()
Bike_object.categories()

Output:

Vehicles have different models
some are two-wheelers and some four-wheelers etc

Vehicles have different models
Car is a four-wheeler

Vehicles have different models
Bike is a two-wheeler

Polymorphism is classified into two types:

  • Compile-time Polymorphism.
  • Run-time Polymorphism

Compile-time Polymorphism:

A compile-time polymorphism, also known as a static polymorphism, is one that is resolved during the program’s compilation. “Method overloading” is a common example.

Run-time Polymorphism:

A running time Polymorphism is also known as dynamic polymorphism because it is resolved during the run time. “Method overriding” is a common example of Run-time polymorphism.

Encapsulation

Encapsulation is the process of wrapping up variables and methods into a single entity. It is a fundamental idea in object-oriented programming (OOP). It works as a protective shield, limiting direct access to variables and methods and preventing accidental or unauthorized data alteration. Encapsulation also turns objects into more self-sufficient, self-contained (independently functioning)units.

Real-time Example

Consider the following real-world example of encapsulation. A company has various sections, such as the accounts and finance sections. The finance department controls all financial transactions and data. The sales department is also in charge of all sales-related activities. They keep track of every sale. A finance officer may require full sales data for a certain month at times. He is not permitted to see the data from the sales area in this case. He must first call another officer in the sales unit to request the data. This is called encapsulation.

Access Modifiers in Encapsulation

While programming, it may be necessary to restrict or limit access to particular variables or functions. This is where access modifiers come into play.

When it comes to access, there are three types of access specifiers that can be utilised while executing Encapsulation in Python. They are:

  • Public Members
  • Private Members
  • Protected Members

Public Members

Members of the public can be accessed from anywhere from a class. By default, all of the class variables are public.

# create a class say employDetails
class employDetails:

    # Create a __init_ constructor which accepts employName and employId as arguments 
    def __init__(self, employName, employId):
        # create public data members
        self.employName = employName;
        self.employId = employId;

    # Create a function say displayEmployId which prints 
    # the employ id when it is called
    def displayEmployId(self): 
        # Access the public data member of the class and print the result
        print("employId: ", self.employId)

# create an object of the class employDetails
employdetails_obj = employDetails("John", 2122);

# Access the public data member of the class and print the result
print("employName: ", employdetails_obj.employName)  

# call the public member function displayEmployId of the class employDetails
employdetails_obj.displayEmployId()

Output:

employName: John
employId: 2122

The variable employName and employId are both public in class employDetails. These data members are available throughout the program.

Private Members

Private members are accessible within the class. To define a private member, use a double underscore “__” before the member name.

Private members and protected members are the same thing. The difference is that private class members should not be accessed by anyone outside the class or its base classes. Private instance variable variables that can be accessed outside of a class do not exist in Python.

Python’s private and secured members can be accessed from outside the class by renaming them.

# create a class say employDetails
class employDetails:
   
   # Create a __init_ constructor which accepts employName and employId as arguments 
   def __init__(self, employName, employId):
      # Create a public variable
      self.employName = employName
      # Create private variable prefixed with "__"
      self.__employId = employId

# create an object of the class employDetails and call it
employdetails_obj = employDetails("John", 2122)

# Access the public variable name of the class and print the result
print("employName:",employdetails_obj.employName)

# Access the private data variable __employId of the class employDetails and print the result
print("employId:",employdetails_obj._employDetails__employId)

Output:

employName: John
employId: 2122

__employId is a private variable in class employDetails; thus, it is accessed by creating an object/instance.

Protected Members

Protected members can be accessed both within the class and by its subclasses. To define a protected member, use a single underscore “_” before the member name.

The protected variable can be accessed from the class and in derived classes (it can even be updated in derived classes), but it is not usually accessed outside of the class body.

The __init__ method(constructor), runs when an object of a type is instantiated.

# create a class say employDetails
class employDetails:
    # Creat which accepts employName and employId as arguments  
    def __init__(self, employName, employId):
        # protected data members as they are prefixed with single underscore "_"
        self._employName = employName
        self._employId = employId

# create object of the class employDetails and call it 
employdetails_obj = employDetails("John", 2122)

# Access the protected members of the class and print the result
print("employName:",employdetails_obj._employName)
print("employId:",employdetails_obj._employId)

Output:

employName: John
employId: 2122

Abstraction

Abstraction hides the unnecessary code/internal details and shows only functionalities. Also, when we do not want to reveal sensitive parts of our code implementation, data abstraction comes into play.

Data abstraction in Python is accomplished by creating abstract classes.

Real-time example

Assume you purchased a movie ticket from BookMyShow via net banking or another method. You have no idea how the pin is generated or how the verification is carried out. This is known as ‘abstraction’ in programming, and it basically means that you only show the implementation details of a specific process and hide the details from the user. It is used to simplify complex problems by modeling problem-specific classes.

 

Python OOPs Concepts Read More »

Comments in Python

Comments are descriptions that help programmers better understand the program’s intent and functionality.

The Python interpreter completely ignores them.

  • Python code can be explained using comments.
  • Comments can be used to improve the readability of the code.
  • When testing code, comments can be used to prevent execution.

Advantages of Comments 

The use of comments in programs improves the readability of our code. It improves the readability of the program and helps us remember why certain blocks of code were written.

Aside from that, comments can be used to ignore certain code while testing other blocks of code. This provides a simple way to prevent the execution of certain lines or to quickly write pseudo-code for the program.

Python comments are classified into three types:

  • Single line Comments
  • Multiline Comments
  • Docstring Comments

Single line Comments

Single-line comments in Python have proven to be useful for providing concise descriptions of parameters, function definitions, and expressions.

To write a single-line comment in Python, use the hash symbol (#) with no white space and continues until the end of the line. If the comment continues to the next line, add a hashtag and resume the conversation.

Example1

# Print the string
print("Good Morning Everyone !!! This is Admin, Hello this is PythonPrograms")

Output:

Good Morning Everyone !!! This is Admin, Hello this is PythonPrograms

Explanation

Here the "Print the string" is the comment. 
The Python interpreter ignores this line.

Everything following # is ignored. As a result, we can write the above program in a single line as shown below:

Example2

print("Good Morning Everyone !!! This is Admin, Hello this is PythonPrograms") # Print the string

Output:

Good Morning Everyone !!! This is Admin, Hello this is PythonPrograms

Explanation

Here it will produce the same results as Example1. 
All the text following (#) is ignored by the interpreter.

Multiline Comments

Multiline comments are not supported in Python. However, there are other methods for writing multiline comments.

  • Writing multiline comments using Multiple Hashtags (#)
  • Writing multiline comments using String Literals

Writing multiline comments using Multiple Hashtags (#):

In Python, we can use multiple hashtags (#) to write multiline comments. Every line will be treated as a single-line comment.

# This is an example for writting multiline comments
# in python using multiple hashtags(#)
print("Good Morning Everyone !!! This is Admin, Hello this is PythonPrograms")

Output:

Good Morning Everyone !!! This is Admin, Hello this is PythonPrograms

Writing multiline comments using String Literals:

Python ignores string literals that are not assigned to a variable, so we can use them as comments.

Example1

# Good Morning Everyone !!! This is Admin, Hello this is PythonPrograms
'Writing multiline comments using String Literals'

Explanation

The second line of the code is a string, but it is not assigned to any
variable or function. As a result, the interpreter ignores the string.

Similarly, we can write multiline comments using multiline strings (triple quotes).

( ‘ )or ( ” ) symbols can be used as the quotation character.

Example2

'''

This is an example for writting multiline comments
in python using string literals

'''
print("Good Morning Everyone !!! This is Admin, Hello this is PythonPrograms")

Output:

Good Morning Everyone !!! This is Admin, Hello this is PythonPrograms

Explanation

The interpreter ignores the multiline string because it is not 
assigned to any variable. It is technically not a multiline comment, 
but it can be used as one.

Python Docstring

Python docstrings are the strings enclosed in triple quotes that appear immediately after the defined function. It’s intended to link documentation created for Python modules, methods, classes, and functions. It is placed immediately beneath the function, module, or class to explain what they do. Using the __doc__ attribute, the docstring is then easily accessible in Python.

A documentation string is a string literal used as the first lines of a code block, such as a function.

A documentation string, unlike a regular comment, can be accessed at runtime via the obj.__doc__ attribute, where obj is the name of the function.

Typically, a documentation string is used to generate code documentation automatically.

Docstrings are documentation strings.

Docstrings are not, strictly speaking, comments. They define anonymous variables that contain references to the strings. They are also not ignored by the Python interpreter.

Python has two types of docstrings:

  • One-line docstrings
  • Multi-line docstrings

One-line docstrings:

A one-line docstring, as the name implies, fits one line. A one-line docstring starts with triple quotes (“””) and ends with triple quotes (“””). There will also be no blank lines before or after the one-line docstring.

Example

def add(x, y):
    """Here it adds the x, y values and print the result"""
    return x+y


# Print the docstring of the above declared add() function 
print(add.__doc__)

Output:

Here it adds the x, y values and print the result

Multi-line docstrings:

A multi-line docstring, as compared to a one-line docstring, can span multiple lines. A multi-line docstring also begins with triple quotes (“””) and ends with triple quotes (“””).

Example

def add(x, y):
    """ Here we are writing the 
        multiline docstrings
        by writing the function that accepts 2 variables
        as arguments      
    """

How Can We Write More Effective Comments?

  • Use comments to describe what a function does rather than the specifics of how it does it.
  • Remove as many redundant comments as you can. Try writing code that can explain itself by using more descriptive function/variable names.
  • Make your comments as brief and concise as possible.

Comments in Python Read More »

enum in Python

Enum is the Python class that is used to create enumerations. Enumeration is a set of symbolic members or names that are bound to constant and unique values. Using these symbolic names, the members of the enumeration can be equated. The enumeration can be repeated over them by itself.

Properties of Enum Class:

  • The type() method allows users to check the types of Enum.
  • Users can display the name of the Enum by using the ‘name’ keyword.
  • Enums can be shown as a string or as a repr.

enum in Python

Method #1: Enum class

Approach:

  • Import Enum class of the enum module using the import keyword.
  • Create a class say Months.
  • Print the enum member as a string.
  • Print the name of the enum member by using “name” keyword.
  • Print the value of enum member by using the “value” keyword.
  • Print the type of enum member using type() function.
  • Print the enum member as repr using the repr() function.
  • Print the list of all the enum members using the list() function.
  • The Exit of the Program.

Below is the implementation:

# Import Enum class of the enum module using the import keyword
from enum import Enum

# Create a class say Months
class Months(Enum):
    January = 1
    Febraury = 2
    March = 3
    April = 4


# print the enum member as string
print(Months.January)

# print the name of the enum member by using "name" keyword
print(Months.January.name)

# print the value of enum member by using the "value" keyword
print(Months.January.value)

# print the type of enum member using type() function
print(type(Months.January))

# print the enum member as repr using the repr() function
print(repr(Months.January))

# print the list of all the enum members using the list() function 
print(list(Months))

Output:

Months.January
January
1
<enum 'Months'>
<Months.January: 1>
[<Months.January: 1>, <Months.Febraury: 2>, <Months.March: 3>, <Months.April: 4>]

Method #2: Printing Enum as an Iterable list

Approach:

  • Import Enum class of the enum module using the import keyword.
  • Create an Enum class say Months (enum class is used for creating enumerations ).
  • Loop in the above Enum class Months using the for loop.
  • Print each member(month) of the Enum class.
  • The Exit of the Program.

Below is the implementation:

# Import Enum class of the enum module using the import keyword
from enum import Enum

# Create a Enum class say Months
# (enum class is used for creating enumerations )
class Months(Enum):
  January = 1
  Febraury = 2
  March = 3
  April = 4
  May = 5
  June = 6
 
print("Enum class(Months) members: ")  
# Loop in the above Enum class Months using the for loop
for month in (Months):  
   # Print each member(month) of the Enum class
   print(month)

Output:

Enum class(Months) members: 
Months.January
Months.February
Months.March
Months.April
Months.May
Months.June

Method #3: Accessing Modes of Enum

There are two ways to access enum members:

  • By value: The value of an enum member is passed in this method.
  • By name: The name of the enum member is passed in this method.

The “name” or “value” keywords can also be used to access a separate value or name.

Approach:

  • Import Enum class of the enum module using the import keyword.
  • Create an Enum class say Months (enum class is used for creating enumerations ).
  • Apply name keyword on the enum class by passing some random value to it to access the enum member by its value.
  • Apply value keyword on the enum class by passing some random name to it to access the enum member by its name.
  • The Exit of the Program.

Below is the implementation:

# Import Enum class of the enum module using the import keyword
from enum import Enum

# Create a Enum class say Months
# (enum class is used for creating enumerations )
class Months(Enum):
  January = 1
  Febrauary = 2
  March = 3
  April = 4
  May = 5
  June = 6

# Apply name keyword on the enum class by passing some random value to it
# to access the enum member by its value
print("The name of Months class with the value 3 = ", Months(3).name)

# Apply value keyword on the enum class by passing some random name to it
# to access the enum member by its name
print("The value of Months class with the name April = ", Months['April'].value)

Output:

The name of Months class with the value 3 = March
The value of Months class with the name April = 4

Method #4: Hashing Enum Class

Members of the Enum class are also known as Enumeration and are hashable. As a result, these members can be utilized for sets and dictionaries.

Approach:

  • Create an Enum class say Vehicle.
  • Create a new empty dictionary for hashing enum member as dictionary
  • Check whether the enum class values are hashed successfully or NOT using the if conditional statement.
  • The Exit of the Program.

Below is the implementation:

import enum

# Create a Enum class say Vehicle
# (enum class is used for creating enumerations )
class Vehicle(enum.Enum):
    bike = 1
    car = 2
    train = 3

# Create a new empty dictionary for hashing enum member as dictionary
dictionary = {}
dictionary[Vehicle.bike] = 'Two wheeler'
dictionary[Vehicle.car] = 'Four Wheeler'

# Check whether the enum calss values are hashed successfully or NOT using the
# if conditional statement
if dictionary == {Vehicle.bike: 'Two wheeler', Vehicle.car: 'Four Wheeler'}:
    print("The Enum class is hashable")
else:
    print("The Enum class is NOT hashable")

Output:

The Enum class is hashable

Method #5: Comparing the Enums

We can easily compare Enums by using the comparison operator.

  • Identity operators- We can compare using the keywords “is” and “is not“.
  • Equality operators- Equality comparisons can be made using “==” and “!=”.

Approach:

  • Import enum module using the import keyword
  • Create an Enum class say Vehicle (enum class is used for creating enumerations ).
  • Compare the enum class members using the identity operator “is” in an if conditional statement.
  • Compare the enum class members using the “!=” in an if conditional statement.
  • The Exit of the Program.

Below is the implementation:

# import enum module using the import keyword
import enum

# Create a Enum class say Vehicle
# (enum class is used for creating enumerations )
class Vehicle(enum.Enum):
    bike = 1
    car = 2
    train = 3

# Compare the enum class members using the identity operator "is"
# in an if conditional statement
if Vehicle.bike is Vehicle.car:
    print("Both bike and car are same vehicles")
else:
    print("Both bike and car are NOT same vehicles")
 
# Compare the enum class members using the "!=" 
# in an if conditional statement
if Vehicle.bike != Vehicle.car:
    print("Both bike and car are NOT same vehicles")
else:
    print("Both bike and car are same vehicles")

Output:

Both bike and car are NOT same vehicles
Both bike and car are NOT same vehicles

enum in Python Read More »

Difference Between List and Tuple in Python

In this tutorial, let us look at the key differences between the list and tuple in python with examples.

List and tuple are data structures in Python that can store one or more objects or values. A list, which can be created with square brackets, is used to store multiple items in one variable. Similarly, tuples, which can be declared with parentheses, can store multiple items in a single variable.
The list has dynamic properties, whereas the tuple has static properties.

List

List objects are declared similarly to arrays in other programming languages. Lists do not have to be homogeneous all of the time, so they can store items of different data types at the same time. As a result, lists are the most useful tool. The list is a Python container data Structure that is used to hold multiple pieces of data at the same time. Lists come in handy when we need to iterate over some elements while keeping hold of the items.

Tuple

A Tuple is a sequence data type that can contain elements of various data types, but it is immutable. A tuple is simply a collection of Python objects separated by commas. Because tuples are static in nature, they are faster than lists.

Let us now look at the major differences between the list and tuple along with the examples.

Difference Between List and Tuple in Python

1)Syntax Differences

The syntax of the list and tuple differs slightly. Lists are denoted by square brackets [], while Tuples are denoted by parenthesis ().

# Give the list as static input and store it in a variable
gvn_lst = [5, 8, 1, 2]
# Give the tuple as static input and store it in a variable
gvn_tuple = (5, 8, 1, 2)

# print the given list
print("The given list = ", gvn_lst)
# print the given tuple
print("The given tuple = ", gvn_tuple)

# print the datatype of given list using the type() function
print("The datatype of given list = ", type(gvn_lst))
# print the datatype of given list using the type() function
print("The datatype of given list = ", type(gvn_tuple))

Output:

The given list = [5, 8, 1, 2]
The given tuple = (5, 8, 1, 2)
The datatype of given list = <class 'list'>
The datatype of given list = <class 'tuple'>

2)List is Mutable where as Tuple is Immutable

A key difference between a list and a tuple is that lists are mutable whereas tuples are immutable. What does this mean exactly? It means that the items in a list can be changed or modified, whereas the items in a tuple cannot be changed or modified.

Because a list is mutable, we cannot use it as a dictionary key. This is due to the fact that a Python dictionary key is an immutable object. As a result, tuples can be used as dictionary keys if necessary.

# Give the list as static input and store it in a variable
gvn_lst = [5, 8, 1, 2]
# Give the tuple as static input and store it in a variable
gvn_tuple = (5, 8, 1, 2)

# Modifying the list element at the index 1
gvn_lst[1] = 10
# print the given list after modification
print("The given list after modification = ", gvn_lst)

# Modifying the tuple element at the index 1
# Here we get an error because as the tuple is immutable, the elements of a tuple cannot be changed
gvn_tuple[1] = 10
print(gvn_tuple)

Output:

The given list after modification = [5, 10, 1, 2]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-306436f9dc4b> in <module>
11 # Modifying the tuple element at the index 1
12 # Here we get an error because as the tuple is immutable, the elements of a tuple cannot be changed
---> 13 gvn_tuple[1] = 10
14 print(gvn_tuple)

TypeError: 'tuple' object does not support item assignment

Explanation:

Here, we assigned 10 to gvn_lst at index 1 and found 10 at index 1
in the output. 
We also got a type error when we assigned 10 to gvn_tuple at index 1. 
We can't change the tuple because it's immutable.

3)Comparison in Size

Tuples operations have a smaller size than list operations, which makes them a little faster, but not by much unless you have a large number of elements.

# Give the list as static input and store it in a variable
gvn_lst = [5, 8, 1, 2, 7, 8, 10, 15, 18, 20]
# Give the tuple as static input and store it in a variable
gvn_tuple = (5, 8, 1, 2, 7, 8, 10, 15, 18, 20)

print('Given list size =', gvn_lst.__sizeof__())
print('Given tuple size =', gvn_tuple.__sizeof__())

Output:

Given list size = 120
Given tuple size = 104

4)Available Functions

Lists have more built-in functions than tuples. We can use the built-in function dir([object] to access all of the list and tuple’s methods.

The number of methods available in these two also differs, with tuples having 33 methods and lists having 46.

# Give the list as static input and store it in a variable
gvn_lst = [5, 8, 1, 2]
# Give the tuple as static input and store it in a variable
gvn_tuple = (5, 8, 1, 2)

print(dir(gvn_lst))
print(dir(gvn_tuple))

Output:

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']

List vs Tuple

                        List                         Tuple
MutableImmutable
In the list, the implication of iterations is time-consuming.Iteration implications are much faster in tuples.
The list performs better for operations like insertion and deletion.Elements can be accessed better in tuples
The Lists consume more memoryWhen compared to a list, a tuple consumes less memory.
Have More built-in functionsTuples have fewer built-in functions when compared to lists
In lists, Unexpected changes and errors are more likely to occur.Tuples rarely generate unexpected errors or changes.

List vs Tuple Similarities

  • Both lists and tuples hold collections of elements and are heterogeneous data types, which means they can hold multiple data types at the same time.
  • They are both ordered, which means the items or objects will remain in the same order in which they were placed until manually changed.
  • We can iterate through the objects they hold because they are both sequential data structures; thus, they are iterable.
  • A square bracketed [index] integer index can be used to access objects of both data types.

Difference Between List and Tuple in Python Read More »