0% found this document useful (0 votes)
0 views

Lab1

Uploaded by

Alex Siryani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Lab1

Uploaded by

Alex Siryani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

🤖

Lab1:Object Oriented
Object-Oriented Design (OOD) Overview
OOD focuses on designing software around objects, emphasizing a data-
centered approach. Objects serve as "black boxes" with specific interfaces
(methods) to interact with them.

Key Steps in OOD


1. Look for Object Candidates

Identify nouns in the problem statement; these may become objects.

Exclude primitive data types (e.g., numbers, strings); focus on entities


grouping related data.

2. Identify Instance Variables

Define what data each object needs (attributes).

Some attributes may be simple (e.g., integers), others may be objects


themselves.

3. Think About Interfaces

Consider actions (verbs) in the problem to define methods.

Ensure all data manipulation is done via these methods.

Lab1:Object Oriented 1
4. Iterate on Design

Switch between designing classes and methods as needed.

Progress isn't linear; adjust and refine as you go.

5. Try Alternatives

Don't hesitate to abandon approaches that don’t work.

Trial and error is part of good design.

6. Keep it Simple

Use the simplest approach that solves the problem.

Avoid unnecessary complexity.

Python Classes Overview


Class: A blueprint for creating objects.

Object: An instance of a class with specific values.

Attributes: Variables within a class, defining its state.

Methods: Functions within a class, defining its behavior.

class Person:
"This is a person class"
age = 10 # Class attribute
def greet(self):
print('Hello')
print(Person.age)
print(Person.greet)

print(Person.__doc__)

Explanation:

The Person class defines a single attribute age and a method greet() .

Lab1:Object Oriented 2
Person.age prints the value of the age attribute (10).

Person.greet outputs the memory location of the method greet .

Person.__doc__ accesses the docstring for the class.

sara = Person()

print(Person.greet)

print(sara.greet)

sara.greet()

Explanation:

sara = Person() creates an instance (object) of the Person class.

sara.greet() calls the greet method. Python automatically passes the object
( sara ) as the first argument, referred to as self .

class Modifiers:
def __init__(self, name):
self.public_member = name # Public attribute

mod = Modifiers("SKAUL05")
print(mod.public_member) # Access the public attribute
mod.public_member = "Github" # Modify the value
print(mod.public_member)

Explanation:

Public members ( public_member ) can be accessed and modified directly outside


the class.

The output shows that the value of public_member is initially "SKAUL05" and later
updated to "Github" .

Lab1:Object Oriented 3
class Modifiers:
def __init__(self, name):
self._protected_member = name # Protected attribute

m = Modifiers("SKAUL05")
print(m._protected_member)

Explanation:

Protected members (prefix _ ) are accessible but conventionally not accessed


directly outside the class.

However, in Python, they can still be accessed (e.g., m._protected_member ).

class Modifiers:
def __init__(self, name):
self.__private_member = name # Private attribute

m = Modifiers("SKAUL05")
print(m.__private_member)

Explanation:

Private members (prefix __ ) cannot be accessed directly outside the class.

Attempting to access m.__private_member raises an AttributeError .

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

def greet(self):
print('Hello, my name is', self.name)

Lab1:Object Oriented 4
p = Person('Sara')
p.greet()

Explanation:

The __init__ method initializes the object’s attributes ( name in this case).

p.greet() outputs a personalized greeting using the name attribute.

class Cat:
animal = 'Cat' # Class variable

def __init__(self, breed):


self.breed = breed # Instance variable

def setColor(self, color):


self.color = color # Instance variable

# Create objects
Mewo = Cat("Bengal")
Mewo.setColor("black")

BsBs = Cat("British Shorthair")


BsBs.setColor("Gray")

print('Mewo details:')
print('Mewo is a', Mewo.animal) # Access class variable
print('Breed: ', Mewo.breed) # Access instance variable
print('Color: ', Mewo.color) # Access instance variable

Explanation:

Class variables ( animal ) are shared among all instances.

Instance variables ( breed , color ) are unique to each object.

Lab1:Object Oriented 5
del BsBs.color # Deletes the color attribute
print(BsBs.color) # Raises an AttributeError

BsBs.setColor("White") # Reassign the color attribute


print(BsBs.color)

del BsBs # Deletes the object


print(BsBs) # Raises an error

Explanation:

del removes attributes or objects.

Accessing deleted attributes or objects results in an error.

class Person:
pass # Placeholder for an empty class

Explanation:

The pass statement is used as a placeholder when defining an empty class or


method to avoid syntax errors.

class Animal:
def setType(self, aType):
self.animalType = aType

def printType(self):
print("Type: ", self.animalType)

class Cat(Animal):
def __init__(self, breed):
self.breed = breed

def setColor(self, color):


self.color = color

Lab1:Object Oriented 6
# Create a Cat object
BsBs = Cat("British Shorthair")
BsBs.setColor("Black")
BsBs.printType() # Call inherited method

print(isinstance(BsBs, Animal)) # Check if BsBs is an instance


print(isinstance(BsBs, Cat)) # Check if BsBs is an instance of

Explanation:

The Cat class inherits methods and attributes from the Animal class.

printType() is an inherited method, and isinstance() checks class relationships.

Lab Solution:
Payroll System Development

Exercise 1: Class Design

Problem Description
A company is developing a payroll system for employees. You are part of the
software development team responsible for the set of classes to represent
expenses.

Specifications
1. Employees can be either:

Hourly-based employees.

Salary-based employees.

Commission-based employees.

2. Each employee has:

Lab1:Object Oriented 7
A first name.

A last name.

An address.

An ID.

3. Hourly-based employees:

Paid a rate per hour for the first 40 working hours per week.

Paid 1.5 times the rate for any hour after that.

4. Salary-based employees:

Have a predetermined weekly salary regardless of the number of hours


worked.

5. Commission-based employees:

Paid a particular percentage of the total sale amount.

6. All employees have a method to calculate and print the total payment per
week.

Task
Draw a class diagram that represents the given problem.

Include:

Constructors.

Setters and getters where appropriate.

The method for calculating the amount of weekly payment.

Take an image of the diagram and upload it to the eLearning system as part of
the answer.

Lab1:Object Oriented 8
Exercise 2: Class Implementation

Problem Description
Write the implementation of the above classes.

Key Points
Implement the classes HourlyEmployee , SalariedEmployee , and CommissionEmployee .

Include:

Constructors to initialize the attributes.

Setters and getters where appropriate.

A calculate_payment method in each class to compute the weekly payment


for the specific type of employee.

class Employee:
def __init__(self,first_name,last_name,address,id):
self.first_name=first_name
self.last_name=last_name
self.address=address
self.id=id
def calculate_payment(self):
return 0

Lab1:Object Oriented 9
class HourlyEmployee(Employee):
def __init__(self,first_name,last_name,address,id,hourly_rate,
super().__init__(first_name,last_name,address,id)
self.hourly_rate=hourly_rate
self.hours_worked=hours_worked
def calculate_payment(self):
if(self.hours_worked<=40):
return self.hourly_rate*self.hours_worked
else:
overtime_hours=self.hours_worked-40
return (self.hourly_rate*40)+(overtime_hours*self.hourly_r

class SalariedEmployee(Employee):
def __init__(self,first_name,last_name,address,id,weekly_salar
super().__init__(first_name,last_name,address,id)
self.weekly_salary=weekly_salary
def calculate_payment(self):
return self.weekly_salary

class CommissionEmployee(Employee):
def __init__(self,first_name,last_name,address,id,sales_amount
super().__init__(first_name,last_name,address,id)
self.sales_amount=sales_amount
self.commission_rate=commission_rate
def calculate_payment(self):
return self.commission_rate*self.sales_amount

Exercise 3: Payroll System Program

Problem Description
Implement a Payroll System program.

Specifications

Lab1:Object Oriented 10
1. Use a single list to store all employees.

2. Prompt the user to enter the number of employees in the company.

3. For each employee:

Prompt the user to enter relevant information.

Create a proper object to store employee information.

4. Write a function named print_paypal that prints the amount to be paid for each
employee.

5. Create a driver (test) program for the Payroll System.

def print_paypal(employees):
print("\nPayroll Summary:")
for employee in employees:
print(
f"Name: {employee.first_name} {employee.last_name},
f"ID: {employee.id}, "
f"Weekly Payment: ${employee.calculate_payment():.2f
)

if __name__ == "__main__":
employees=[]
num_of_emp=int(input('Enter number of employees:'))

for i in range(num_of_emp):
print(f"\n Enter the details for the Employee {i+1}")
first_name=input("Enter the first name:")
last_name=input("Enter the last name:")
address=input("Enter the address:")
id=input("Enter the id:")

print("\nSelect the type of employee:")


print("1. Hourly Employee")
print("2. Salaried Employee")

Lab1:Object Oriented 11
print("3. Commission Employee")

choice=int(input("Enter your choice:"))

if choice==1:
hourly_rate=float(input("Enter the hourly rate:"))
hours_worked=float(input("Enter the hours worked:"))
employee=HourlyEmployee(first_name,last_name,address,id,ho

elif choice==2:
weekly_salary=float(input("Enter the weekly salary:"))
employee=SalariedEmployee(first_name,last_name,address,id,

elif choice==3:
sales_amount=float(input("Enter the sales amount:"))
commission_rate=float(input("Enter the commission rate:"))
employee=CommissionEmployee(first_name,last_name,address,i

else:
print("Invalid choice.Exiting...")

employees.append(employee)

print_paypal(employees)

Sample Output:

Lab1:Object Oriented 12
Lab1:Object Oriented 13

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy