Python Basic Tutorials

Python is a high level general purpose programming language which has a clear/easy learning curve. Python programming language is massively used in various domains like Artificial Intelligence, Data Science, Web Development, Utilities Tools and Scripts and many more

Python is a Programming language, and the default Python we use is written in C programming language which is also referred to as CPython (Python implementation in C). There are various implementation of Python Programming language i.e Jython(in JAVA), Skulpt(in JS) e.t.c

To make everything easy: We refer CPython as Python

OOP in Python

What is object-oriented programming?

Object-oriented programming is the programming paradigm in which we create classes and objects to solve any kind of programming problem rather than creating functions and sequential codes.

Everything in this world is an object, and every object should have its own attributes and behavior. Attributes are the fields of an object. In programs, attributes are simply the variables. Behaviors refer to what tasks that object can do. In programs, Behaviours are simply the method or a function.

For instance, let's take a car as an example of an object. Attributes of a car would be name, color, capacity,weight. The behavior of a car would be starting the engine, turning left/right, accelerating, braking, turning on/ off wipers, etc.

Let's take a dog as another example of an object. Attributes of a dog would be its name, color, height, legs, etc. The behavior of a dog would be barking, running, eating, sleeping, etc.

In this programming paradigm, we design a class of objects, based on the attributes and behavior of that class multiple objects of the same attributes and behavior can be created. This approach of programming will be more readable, reusable, and efficient.

Class

Simply, a class is a blueprint for the objects. In another way, it is the designation of the objects.

Any class is created using the 'class keyword'. It's syntax is:


class ClassName:
    #attributes
    #methods
    
Example

Let us create a class of dogs. In high-level terms, let us design a dog. To create a dog class, we should implement its attributes and behaviors in the class.


class Dog:
    species="Animal" #class attributes

    def __init__(self,name,color): #class method
        self.name=name
        self.color=color

    def bark(self): #class method
        print("Barking...")
    

The variable which is declared inside the class and outside the __init__() method is known as a class variable or a class attribute. It will be the same for all the objects created with that class. In the above example, species is a class variable.

The variable which is declared inside a class and also inside the __init__() method is known as an instance variable. These variables can be different for different objects created using even the same class. In the above example, name & color are the instance variables.

What is Object?

An object is an instance of a class. A class is the blueprint of an object. With the help of a class, we can create multiple objects having similar properties as designed in that class.

Creating an object of a Class

Let us create a class of a computer and make it's two new objects.


class Computer:
    def __init__(self,name,ram):
        self.name=name
        self.ram=ram

computer1 = Computer("Macbook","8GB") #object1
computer2 = Computer("Acer", "16 GB") #object2

print(computer1.name)
print(computer1.ram)
print(computer2.name)
print(computer2.ram) 
Output

Macbook
8GB
Acer
16 GB

The __init__() Method

The __init__() method is a special method in python that is used to initialize the attributes/variables of a class. It is similar to the concept of constructor in other programming languages like java, c++, etc. Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object creation.

Inside the __init__() method, the initial values of class attributes are set.

Example

class Cat:
    def __init__(self, name, age):
        """This is __init__() method which is used to initialize the variables"""
        self.name=name
        self.age=20

cat1 = Cat("Tom",20)
print(cat1.name)
print(cat1.age) 
Output:

Tom
20

Here, the self keyword is mandatory as an argument of the __init__() method. Each time you create the new object from the class, the __init__() method is automatically called.


class Phone:
    def __init__(self):
        print ("Init method is called")

nokia = Phone()
samsung = Phone()
iphone = Phone()
Output

As the objects are created 3 times using Phone class, The __init__() method is called 3 times.


Init method is called
Init method is called
Init method is called 
Methods

As we've discussed, A class should have its attributes and behaviors. Here, attributes are all the variables in OOP programming inside any class, but the behaviors refer to what task, an object of any class can do. Basically, methods are like functions that denote the behavior of any class. Similar to the function, methods are created using the 'def' keyword.

Example

Let us create a class of a calculator that can perform various operations.


class Calculator:
    def __init__(self,num1,num2):
        self.num1=num1
        self.num2=num2

    def sum(self):
        return self.num1 + self.num2

    def subtract(self):
        if self.num1>self.num2:
            return self.num1-self.num2
        return self.num2-self.num1

    def multiply(self):
        return self.num1*self.num2

    def divide(self):
        return self.num1/self.num2

calculator = Calculator(5,10)
print("Sum:" ,calculator.sum())
print("Subtract:" , calculator.subtract())
print("Multiply:" , calculator.multiply())
print("Divide:" , calculator.divide())
Output

Sum: 15
Subtract: 5
Multiply: 50
Divide: 0.5
 
Types of method

There are three kinds of methods, these are Instance methods, Class methods, Static methods.

The basic method which deals with the instance variables, not with the class variable is known as Instance methods.

Instance methods are also of two types, they are accessors and mutators.

Accessors are also called getters which help to get the values. Mutators are also called setters which help to set or assign the values.

The method which deals with the class variables is known as the class method. we use the @classmethod decorator for class method definition. In the following code, there is school as a class variable.

Syntax:

@classmethod
def fun(cls,arg1,arg2,...):
    # your code
    

The method which deals neither with class variables nor with instance variables is known as the static method. we use the @staticmethod decorator for static method definition.

Let us demonstrate each methods creating a class of Students.


class Student:
    school='PythonTheRightWay School'

    def __init__(self,m1,m2,m3) -> None:
        self.m1=m1
        self.m2=m2
        self.m3=m3

    def average(self): #this is instance method.
        return (self.m1+self.m2+self.m3)/3

    #accessors only help to fetch the values, they are getters.
    def getm1(self):
        return self.m1

    #mutators help to modify the values, they are setters
    def setm1(self,value):
        self.m1=value

    @classmethod
    def info(cls): #classmethod dealing with class variable.
        return cls.school

    @staticmethod
    def stat(): #static method definition.
        print("This is the static method.")

s1=student(12,32,34)

print("Before using setter, mark1: ",s1.getm1(), "Average: ",s1.average()) #using getter here

s1.setm1(30) #setting mark1 = 30

print("After using setter, mark1: ",s1.getm1(), "Average: ",s1.average()) #using getter here

#lets print the class method by calling it
print(student.info())

# let's print the static method by calling it.
student.stat() 
Output

Before using setter, mark1: 12 Average: 26.0
After using setter, mark1: 30 Average: 32.0
PythonTheRightWay School
This is the static method.
    
The self keyword.

self represents an instance of a class. It binds the attributes with the given arguments. Basically self points to the current object or instance.


class Check:
    def __init__(self):
        print("Address of self = ",id(self))

obj = Check()
print("Address of class object = ",id(obj))

Output

Address of self = 2993263140672
Address of class object = 2993263140672
 

When we use self it helps to identify the current calling object.

Example

class Student:
    def info(self):
        return f"Name: {self.name}\nAge: {self.age}\nRoll_no: {self.roll_no}"

ram = Student()
hari = Student()

ram.name="Ram"
ram.age=21
ram.roll_no=3


hari.name="Hari"
hari.age=23
hari.roll_no=5

print(ram.info())
print(hari.info())
Output

Name: Ram
Age: 21
Roll_no: 3
Name: Hari
Age: 23
Roll_no: 5