Lecture 10
Lecture 10
and Objects
Lecture 10
Making classes and objects
class Employee:
name = ""
age = 0
How to create objects?
a = Employee()
b = Employee()
How are a and b different?
a = Employee()
b = Employee()
a.name = "Carol"
a.age = 31
b.name = "Majid"
b.age = 22
What is a Class Diagram?
Class Name
• Property 1
• Property 2
• Property 3
• Behavior / Action 1
• Behavior / Action 2
• Behavior / Action 3
• Behavior / Action 4
Employee Class
Employee
• Name
• Hourly Rate
• Hours Worked
• Pay Salary
• Calculate Salary
• Add hours worked
• Fire
What’s in the Employee class?
• Calculate Salary
How to create a class in Python?
class Employee:
name = ""
age = 0
hourlyRate = 0
hoursWorked = 0
Remember Functions?
def calculateSalary(self):
return self.hourlyRate * self.hoursWorked
Add functions to class as behaviors
Employee
class Employee: • Name
• Age
name = "" • Hourly Rate
• Hours Worked
age = 0
hourlyRate = 5 • Calculate Salary
hoursWorked = 7
def calculateSalary(self):
return self.hourlyRate * self.hoursWorked
Using Employee Class
x = Employee()
x.name = “Karen”
x.age = 22
x.hourlyRate = 15
x.hoursWorked = 7
print(x.calculateSalary())
Just one object?
x = Employee() y = Employee()
x.name = “Karen” y.name = “Mark”
x.age = 22 y.age = 28
x.hourlyRate = 15 y.hourlyRate = 14
x.hoursWorked = 7 y.hoursWorked = 8
print(x.calculateSalary()) print(y.calculateSalary())
Let’s create a Student class
Student
• Name
• Address
• Roll no
• Study
• Eat
• Beat
• Print
Define Behavior
def study():
print("I'm studying and it's boring")
Behavior/Method
def eat():
print("Yum yum yum")
Behavior/Method
def beat():
print("Oh uh *** why are you hitting me?")
Behavior/Method
def print(self):
print(self.name, self.address, self.rollno)
Class
def study(self):
print("I'm studying and it's boring")
def beat(self):
print("Oh uh *** why are you hitting me?")
def print(self):
print(self.name, self.address, self.rollno)
Student Object
s = Student()
s.eat()
s.beat()
s.study()
Only one object?
s = Student()
t = Student()
another = Student()
x = Student()
newstudent = Student()
s.eat()
t.beat()
x.study()
Objects
s.print()
s.eat()
t.print()
t.eat()
x.print()
x.eat()
a.print()
a.eat()
Personalizing Behaviors
s = Student("Ahmed", "Lahore", 55)
t = Student("Kiran", "Peshawar", 25)
x = Student("Jawad", "Karachi", 51)
Ahmed Lahore 55
a = Student("Maria", "Islamabad", 50)
Ahmed eats, yum yum yum
Kiran Peshawar 25
s.print()
Kiran eats, yum yum yum
s.eat()
Jawad Karachi 51
t.print()
Jawad eats, yum yum yum
t.eat()
Maria Islamabad 50
x.print() Maria eats, yum yum yum
x.eat()
a.print()
a.eat()