Skip to main content

OOPs Programming

Class

 1.  simple class sum

    class Number:
        def sum(self):
            return self.a + self.b

    num = Number()
    num.a = 12
    num.b = 34
    s = num.sum()
    print(s)

    # a = 12
    # b = 34

    # print("The sum of a and b is ", a+b)

    '''
    PascalCase 
    EmployeeName -->PascalCase 

    camelCase
    isNumeric, isFloatOrInt -->camelCase

>> 46

2. Railway OOps

    import pandas as pd

    pd.DataFrame()
    class RailwayForm:
        formType = "RailwayForm"
        def printData(self):
            print(f"Name is {self.name}")
            print(f"Train is {self.train}")

    harrysApplication = RailwayForm()
    harrysApplication.name = "avi"
    harrysApplication.train = "Hutatma Express"
    harrysApplication.printData()

>>Name is avi

Train is Hutatma Express

3. Game Example

    class Remote():
        pass

    class Player:
        def moveRight(self):
            pass

        def moveLeft(self):
            pass

        def moveTop(self):
            pass

    remote1 = Remote()
    player1 = Player()

    if(remote1.isLeftPressed()):
        player1.moveLeft()

>>

4. Employee class

    class Employee:
        company = "Google"
        salary = 100

    harry = Employee()
    rajni = Employee()
    harry.salary = 300
    rajni.salary = 400

    print(harry.company)
    print(rajni.company)
    Employee.company = "YouTube"
    print(harry.company)
    print(rajni.company)
    print(harry.salary)
    print(rajni.salary)

>>Google

Google

YouTube

YouTube

300

400

5.instace class

    class Employee:
        company = "Google"
        salary = 100

    harry = Employee()
    rajni = Employee()

    # Creating instance attribute salary for both the objects
    # harry.salary = 300
    # rajni.salary = 400
    harry.salary = 45
    print(harry.salary)
    print(rajni.salary)

    # Below line throws an error as address is not present in instance/class 
    # print(rajni.address) 

>>45

100

6. Self 

    class Employee:
        company = "Google"
        def getSalary(self):
            print(f"Salary for this employee working in {self.company} is {self.salary}")

    harry = Employee()
    harry.salary = 100000
    harry.getSalary() # Employee.getSalary(harry)

>> Salary for this employee working in Google is 100000

7. static method

    class Employee:
        company = "Google"

        def getSalary(selfsignature):
            print(f"Salary for this employee working in {self.company} is {self.salary}\n{signature}")

        @staticmethod
        def greet():
            print("Good Morning, Sir")

        @staticmethod
        def time():
            print("The time is 9AM in the morning")

    harry = Employee()
    harry.salary = 100000
    harry.getSalary("Thanks!"# Employee.getSalary(harry)
    harry.greet() # Employee.greet()
    harry.time()

>>Salary for this employee working in Google is 100000

Thanks!

Good Morning, Sir

The time is 9AM in the morning

8. constructor

class Employee:
    company = "Google"

    def __init__(selfnamesalarysubunit):
        self.name = name
        self.salary = salary
        self.subunit = subunit
        print("Employee is created!"

    def getDetails(self):
        print(f"The name of the employee is {self.name}")
        print(f"The salary of the employee is {self.salary}")
        print(f"The subunit of the employee is {self.subunit}")

    def getSalary(selfsignature):
        print(f"Salary for this employee working in {self.company} is {self.salary}\n{signature}")

    @staticmethod
    def greet():
        print("Good Morning, Sir")

    @staticmethod
    def time():
        print("The time is 9AM in the morning")

harry = Employee("Harry"100"YouTube")
# harry = Employee() --> This throws an error (missing 3 required positional arguments:)
harry.getDetails()

>>

Employee is created!

The name of the employee is Harry

The salary of the employee is 100

The subunit of the employee is YouTube

9. store information of programmer working in microsoft

class Programmer:
    company = "Microsoft"

    def __init__(selfnameproduct):
        self.name = name
        self.product = product

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


harry = Programmer("Harry""Skype")
alka = Programmer("Alka""GitHub")
harry.getInfo()
alka.getInfo()

>>The name of the Microsoft programmer is Harry and the product is Skype

The name of the Microsoft programmer is Alka and the product 

is GitHub

10. class calculator to fine square, cube, squareroot

class Calculator:
    def __init__(selfnum):
        self.number = num

    def square(self):
        print(f"The value of {self.number} square is {self.number **2}")

    def squareRoot(self):
        print(f"The value of {self.number} square root is {self.number **0.5}")

    def cube(self):
        print(f"The value of {self.number} cube is {self.number **3}")

a = Calculator(9)
a.square()
a.squareRoot() 
a.cube()

>>The value of 9 square is 81

The value of 9 square root is 3.0

The value of 9 cube is 729

11.

class Sample:
    a = "avi"

obj = Sample()
obj.a = "Vikky"
# Sample.a = "Vikky"

print(Sample.a)
print(obj.a)

>>avi

Vikky

12. Static method in problem 10 calculator

class Calculator:
    def __init__(selfnum):
        self.number = num

    def square(self):
        print(f"The value of {self.number} square is {self.number **2}")

    def squareRoot(self):
        print(f"The value of {self.number} square root is {self.number **0.5}")

    def cube(self):
        print(f"The value of {self.number} cube is {self.number **3}")
    
    @staticmethod
    def greet():
        print("*******Hello there welcome to the best calculator of the world*******")

a = Calculator(9)
a.greet()
a.square()
a.squareRoot() 
a.cube()

>>*******Hello there welcome to the best calculator of the world*******

The value of 9 square is 81

The value of 9 square root is 3.0

The value of 9 cube is 729

13. Train status

'''
1 2 3 4 5 6 7 8 9 10
'''

class Train:
    def __init__(selfnamefareseats):
        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(selfseatNo):
        pass

intercity = Train("Intercity Express: 14015"902)
intercity.getStatus() 
intercity.bookTicket()
intercity.bookTicket()
intercity.bookTicket()
intercity.getStatus()

>>************

The name of the train is Intercity Express: 14015

The seats available in the train are 2

************

Your ticket has been booked! Your seat number is 2

Your ticket has been booked! Your seat number is 1

Sorry this train is full! Kindly try in tatkal

************

The name of the train is Intercity Express: 14015

The seats available in the train are 0

************

1. can you change parameter self in class ?? 

class Sample
    def __init__(slfname):
        slf.name = name

obj = Sample("Harry"
print(obj.name

>> yes we can change self to any word

1.1.

>>

1.

>>

1.1.

>>

1.

>>

1.1.

>>

1.

>>

1.1.

>>

1.

>>

1.1.

>>

1.

>>

1.1.

>>

1.

>>


Popular posts from this blog

deploying Machine learning Model : pkl, Flask,postman

1)Create model and train          #  importing Librarys         import pandas as pd         import numpy as np         import matplotlib . pyplot as plt         import seaborn as sns         import requests         from pickle import dump , load         # Load Dataset         url = "http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"         names = [ "sepal_length" , "sepal_width" , "petal_length" , "petal_width" , "species" ]         # Loading Dataset         df = pd . read_csv ( url , names = names )         df . tail ( 11 )         df . columns         test = [         { 'sepal_length' : 5.1 , 'sepal_width' : 3.5 , 'peta...

Binomial Distribution

  The binomial distribution formula is:                                                    b(x; n, P) =  n C x  * P x  * (1 – P) n – x Where: b = binomial probability x = total number of “successes” (pass or fail, heads or tails etc.) P = probability of a success on an individual trial n = number of trials Note:  The binomial distribution formula can also be written in a slightly different way, because  n C x  = n! / x!(n – x)! (this binomial distribution formula uses factorials  (What is a factorial? ). “q” in this formula is just the probability of failure (subtract your probability of success from 1). Using the First Binomial Distribution Formula The binomial distribution formula can calculate the probability of success for binomial distributions. Often you’ll be told to “plug in” the numbers to the  formul...

cammand for installing library in python

 Command for installing in jupyter notebook:                pip install library_name                ex. pip install nump installing from anaconda prompt:           1. pip install numpy           2.   conda install -c conda-forge matplotlib search for conda command for matplotlib and go to official website. Installing from anaconda navigator easy. Somtime give error then open as administrator