Sunday, June 6, 2021

Python - Object-Oriented Programming

Solving a problem by creating objects is one of the most popular approaches in programming. This is called object-oriented programming.This concept focuses on using reusable code. (Implements DRY principle)

Class

A class is a blueprint for creating objects.

The syntax of a class looks like this:

Class Employee: [classname is written in PascalCase]

#methods & variables

Object

An object is an instantiation of a class. When class is defined, a template(info) is defined. Memory is allocated only after object instantiation.

Objects of a given class can invoke the methods available to it without revealing the implementation details to the user.     #Abstraction & Encapsulation!

Modelling a problem in OOPs

We identify the following in our problem

Noun -> Class -> Employee

Adjective -> Attributes -> name,age,salary

Verbs -> Methods -> getSalary(), increment()


Class Attributes

An attribute that belongs to the class rather than a particular object.

Example:

Class Employee:

company = “Google” #Specific to each class

harry = Employee() #Object instantiation

harry.company

Employee.company = “YouTube” #changing class attribute

Instance Attributes

An attribute that belongs to the Instance (object)

Assuming the class from the previous example:

harry.name = “Harry”

harry.salary = “30K” #Adding instance attributes

Note: Instance attributes take preference over class attributes during assignment and retrieval.


‘self’ parameter:

self refers to the instance of the class.

It is automatically passed with a function call from an object.

harry.getSalary()

here, self is harry and above line of code is equivalent to Employee.getSalary(harry)

This function getsalary is defined as:

class Employee:

company = “Google”

def getSalary(self):

print(“Salary is not there”)

Static method:

Sometimes we need a function that doesn’t use the self-parameter. We can define a static method like this:

@staticmethod #decorator to mark greet as a static method

def greet():

print(“Hello user”)


__init__() constructor:

  • __init__() is a special method which runs as soon as the object is created.
  • __init__() method is also known as constructor.
  • It takes self-argument and can also take further arguments.

For Example:

class Employee:

def __init__(self,name):

self.name = name

def getSalary(self):

#Some code…

harry = Employee(“Harry”) #Object can be instantiated using constructor like this!

 


Practice:

Create a class programmer for storing information of a few programmers working at Microsoft.

class Programmer:
    company = "Microsoft"
    def __init__(self,name,product):
        self.name=name
        self.product=product

    def getInfo(self):
        print(f"name of the companty {self.company} and name is {self.name} and product is {self.product}")

sri=Programmer("Sri","Skype")
nanda=Programmer("Nannda","Outlook")
print(sri.getInfo())
print(nanda.getInfo())

Write a class calculator capable of finding square, cube and the square root of a number.

class Calculator:

    def __init__(self,num):
        self.num=num
    def getSquare(self):
        return self.num * self.num

    def getCube(self):
        return self.num ** 3

    def getSqrRoot(self):
        return  self.num * 0.5

c=Calculator(5)
print(c.getSquare())
print(c.getCube())
print(c.getSqrRoot())

Create a class with a class attribute a; create an object from it and set a directly using object.a=0 Does this change the class attribute?

class Sample:
    a=23

s = Sample()
s.a=0
print(Sample.a)
print(s.a)

Answer: No, This will not change the class attribute.

Add a static method in problem 2 to greet the user with hello.

class Calculator:

    def __init__(self,num):
        self.num=num
    def getSquare(self):
        return self.num * self.num

    def getCube(self):
        return self.num ** 3

    def getSqrRoot(self):
        return  self.num * 0.5
    
    @staticmethod
    def greetUser():
        print("Hello user")

c=Calculator(5)
c.greetUser()
print(c.getSquare())
print(c.getCube())
print(c.getSqrRoot())

Write a class Train which has methods to book a ticket, get status(no of seats), and get fare information of trains running under Indian Railways.

class Train:

    def __init__(self, name, fare, seats):

        self.name = name

        self.fare = fare

        self.seats = seats


    def getStatus(self):

        print("************")

        print(f"The name of the train is {self.name}")

        print(f"The seats available in the train are {self.seats}")

        print("************")


    def fareInfo(self):

        print(f"The price of the ticket is: Rs {self.fare}")


    def bookTicket(self):

        if(self.seats>0):

            print(f"Your ticket has been booked! Your seat number is {self.seats}")

            self.seats = self.seats - 1

        else:

            print("Sorry this train is full! Kindly try in tatkal")


    def cancelTicket(self, seatNo):

        pass


intercity = Train("Intercity Express: 14015", 90, 2)

intercity.getStatus() 

intercity.bookTicket()

intercity.bookTicket()

intercity.bookTicket()

intercity.getStatus()


 


No comments:

Post a Comment

Featured Post

OIC - Restrictions on Using Stage File Action Operations with the File/Attachment Features of the Connectivity Agent

Restrictions on Using Stage File Action Operations with the File/Attachment Features of the Connectivity Agent When configuring the stage fi...