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

Python L07 ClassObj

Uploaded by

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

Python L07 ClassObj

Uploaded by

Ahmed Osta
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 47

CSIT110

Python

School of Computing and Information Technology University of Wollongong


Class and Object

OBJECTIVES:

● Understand the concepts of Class and Object

○ Define class, create object


○ Instance attribute vs Class attribute
○ Instance method
○ Special (dunder) method
○ Static/Class method

2
Class and object

Object instance
0973427
John Smith

Class Student Object instance


Is a blueprint for
1882845
Mary Wilson

Class allows us to group data and


functionality together.
Object instance
Class provides a blueprint for creating 0729032
individual object instances . Ye Yang

3
Class and object

Class specifies what kind of data an object can hold

Class Staff

Staff number
Employment type (Full time/Part time/Casual)
First name
Last name
Date of birth
...

Class TV_Program

Channel name
Program title
Start time
End time
Category
... 4
Class and object

An object is an instance of a class.

The terms object and instance are used interchangeably.

Each object instance has its own data values.

Staff Object 1

Staff number = 024161


Employment type = Full time Staff Object 2
First name = John ---------------------------
Last name = Smith Staff number = 952160
Date of birth = 14/01/2000 Employment type = Casual
... First name = Frogory
Last name = Green
Date of birth =
27/04/2001
...
5
Class and object

Each object is a member of a certain class.

TV_Program Object 1

Channel name = SBS


Program title = FIFA 2018: Uruguay v Russia
Start time = 25/06/2018 21:00
End time = 26/06/2018 01:15
Category = Sport
...

TV_Program Object 2

Channel name = ABC


Program title = Bigfoot Family
Start time = 15/03/2021 19:30
End time = 15/03/2021 21:00
Category = Movies
...
6
Instance attribute vs Class attribute

Some information belongs to individual object instance.

Some other information is common to all objects.

Instance attribute: data belongs to individual object instance.

Class attribute: data that is common to all objects.


(Some classes do not have any class attributes.)

7
Instance attribute vs Class attribute

Instance attribute: data belongs to individual object instance.


For example,

● Each student object has its own first name, last name and student id,
etc...

● Each staff object has its own staff id, date of birth, employment type,
etc…

● Each TV program object has its own channel name, program title, start
time, end time, etc...

8
Instance attribute vs Class attribute

class Student:
#{

email_domain = "solla.sollew.edu"
student_dir = "/user/student" class attributes

def init (self, id, first_name, last_name):


#{
self.id = id
self.first_name = first_name object/instance attributes
self.last_name = last_name
...
#}

#}

Instance attribute: data belong to individual object instance.


In Python, instance attributes usually get initialised in the special method
called init
9
Instance attribute vs Class attribute

Class attribute: data that is common to all objects.


(Some classes do not have any class attributes.)

For example,

● All students share the same email domain solla.sollew.edu

● All students share the same Unix student directory /user/student

● All staffs share the cloud work directory /prv/doc/staff

10
Instance attribute vs Class attribute

class Student:
#{

email_domain = "solla.sollew.edu"
student_dir = "/user/student" class attributes

def init (self, id, first_name, last_name):


#{
self.id = id
self.first_name = first_name object/instance attributes
self.last_name = last_name
...
#}

#}

Class attribute: data that is common to all objects.

11
Instance method vs Class/Static method

Instance method:
● Deal with a particular individual object instance

Static / Class method:


● Do NOT deal with individual object instance
● Common to all object instances

12
Instance method vs Class/Static method

Instance method:
● Deal with particular individual object instance

For example:
● Get the full name of a Student object

● Get the email address of a Staff object

● Update the title of a TV-Program object

● Update the start time of a TV-Program object


13
Instance method vs Class/Static method

Instance method:
● Deal with individual object instance attributes
● The first argument (self) is always referred to the
object instance
class Student:
#{

def init (self, id, first_name,

last_name)... def repr (self)...

def fullname(self)...

def print_detail(self)...

#}
14
Instance method vs Class/Static method

Instance method:
● Deal with individual object instance attributes
● The first argument (self) is always referred to the
object instance
class TV_Program:
#{

def init (self, channel, title,

start_time,...)... def str (self)...

def get_length_in_minutes(self)...

def time_left_in_minutes(self, reference_time)...

#}
15
Instance method vs Class/Static method

Instance method:
● instance method can be invoked from an object

staff2.update_employment_type("Casual")
staff3.update_employment_type("Fulltime")

length2 = tv_program2.get_length_in_minutes()
length5 = tv_program5.get_length_in_minutes()

minute_count5 = tv_program5.time_left_in_minutes(now)
minute_count3 = tv_program3.time_left_in_minutes(now)

16
Instance method vs Class/Static method

Static / Class method:


● Do NOT deal with an individual object instance
● Common to all object instances

For example:
● Get the shared student email domain (solla.sollew.edu)

● Get the total number of students

● Get the total number of TV programs on a certain


channel on a certain day
17
Instance method vs Class/Static method

Static / Class method:


● static/class method can be invoked from class name

contact_email = Student.admin_email()

url = Student.uni_website()

studentObj = Student.find_by_student_id("0783122")

tv_program_list1 = TV_Program.find_by_time(now)

tv_program_list2 = TV_Program.find_by_channel("SBS", now)

18
Instance method vs Class/Static method

Class method vs static method:


● The first argument (cls) of a class method is always
referred to the class
class Student:
#{
email_domain = "solla.sollew.edu"
student_dir = "/user/student"

@classmethod
def admin_email(cls):
return "admin@" + cls.email_domain

@staticmethod
def uni_website():
return "http://www.solla.sollew.edu"

#}
19
Defining class and creating object

class Fish:
#{

def init (self, name, color,


address): #{
self.name = name
self.color = color object attributes
self.address = address
#}

#}

# creating fish objects


shark = Fish("Bruce", "gray", "Sydney aquarium")

goldfish = Fish("Goldie", "orange", "Darling River")

angelfish = Fish("Finley", "blue", "Joe’s fish tank")

20
Defining class and creating object
class Student:
#{

def init (self, id, first_name,


last_name): #{
self.id = id
self.first_name = first_name
object attributes
self.last_name = last_name
#}

#}

# creating student objects


student1 = Student("0973427", "John", "Smith")

student2 = Student("1882845", "Mary", "Wilson")

student3 = Student("0729032", "Ye", "Yang")


21
Accessing object instance attributes

class Fish:

def
init
(self,
name,
# color,
creating fish objects
address):
shark = Fish("Bruce", "gray", "Sydney aquarium")
... = Fish("Goldie", "orange", "Darling River")
goldfish
angelfish = Fish("Finley", "blue", "Joe’s fish tank")

# get object attributes


print(shark.name)
print(shark.color)
print(shark.address)

22
Accessing object instance attributes

class Student:

def init (self, id, first_name, last_name):


...

# creating student objects


student1 = Student("0973427", "John", "Smith")
student2 = Student("1882845", "Mary", "Wilson")
student3 = Student("0729032", "Ye", "Yang")

# get object attributes


print(student1.id)
print(student1.first_name)
print(student1.last_name)

23
Modify object instance attributes
angelfish = Fish("Finley", "blue", "Joe’s fish tank")

# display object attributes


print("Before: ")
print(angelfish.name)
print(angelfish.color)
print(angelfish.address)

# change fish address


angelfish.address = "Uni duck pond"

# display object attributes after update


print("After: ")
print(angelfish.name)
print(angelfish.color)
print(angelfish.address)

Before: After:
Finley Finley
blue blue
Joe’s Uni 25
Modify object instance attributes
student2 = Student("1882845", "Mary", "Wilson")

# display object attributes


print("Before: ")
print(student2.id)
print(student2.first_name)
print(student2.last_name)

# change student last name


student2.last_name = "Davis"

# display object attributes after update


print("After: ")
print(student2.id)
print(student2.first_name)
print(student2.last_name)

Before: After:
1882845 1882845
Mary Mary
Wilson Davis 26
Defining an object instance method

class Student:
#{
. . .

def fullname(self):
#{

return self.first_name + " " + self.last_name

#}

#}

Instance method:
● Automatically pass the object instance (self) as the
first parameter
26
Defining an object instance method

class Student:

def fullname(self):
#{

return self.first_name + " " + self.last_name

#}

# creating a student object


student1 = Student("0973427", "John", "Smith")

# calling method - from the object instance


print(student1.fullname())

27
Documenting Python code

class Student:
#{
"""
Class Student represents a student
"""

def fullname(self):
#{
"""
Get student's full name
"""
return self.first_name
+ " " + self.last_name
#}

#}
It is important to write documentation of your class and methods.
This helps users to understand the usage and functionality of your code.

help(Student) 29
Help method

print(help(Student))

class Student(builtins.object)
| Class Student represents a student
| with the following attributes:
| id: student number
| first_name: first name
| last_name: last name
| username: Unix account username
|
| Methods defined here:
|
| init (self, id, first_name, last_name)
| Initialize self. See help(type(self)) for accurate signature.
|
| repr (self)
| Return repr(self).
|
| str (self)
| Return str(self).
|
| email(self)
| Get student's email: username@domain
|
| email_alias(self)
| Get student's friendly-looking email:
| firstname.lastname.3IDdigits@domain
|
| fullname(self)
| Get student's full name
|
| home_dir(self)
| Get student's Unix home directory: studentDir/username
|
| print_detail(self)
| Display student detail
|
|
| Data descriptors defined here:
|
| dict
| dictionary for instance variables (if defined)
|
| weakref
| list of weak references to the object (if defined)
|
|
| Data and other attributes defined here:
|
| email_domain = 'solla.sollew.edu'
|
| student_dir = '/user/student' 30
Case study example:

Consider a fictional University called Solla Sollew where


● Each student is given a unique student id (for example, student John Smith
has student id 0973427)
● Each student has a username constructed from the first name initial, the last
name initial and the first 3 digits of the student id (John Smith username is
js097)
● Student username is constructed at the enrolment day and will never be
changed even though student may change their name.
● Each student is given a Unix home directory (John Smith home
directory is
/user/student/js097)
● Each student is given an email and it will never be changed even though
student may change their name (John Smith email is
[email protected])
● Each student is given an email alias (John Smith email alias is
[email protected]).
● When student name is changed then this alias also gets changed automatically
(for example, if John Smith last name changed to Lee then his email alias
is automatically changed to [email protected]) 30
Defining class Student

class Student:
"""
Class Student represents a student
with the following attributes:
id: student number
first_name: first name
last_name: last name
username: Unix account username
"""

email_domain = "solla.sollew.edu"
student_dir = "/user/student" class attributes

def init (self, id, first_name, last_name):


...
object attributes

31
Defining class Student

class Student:
def init (self, id, first_name, last_name):
self.id = id
self.first_name = first_name
self.last_name = last_name
object attributes
# username is constructed in the beginning
# and will not change if name changed
# username = lowercase initials + first 3 id digits
self.username = first_name[0].lower() + last_name[0].lower() + id[0:3]

# creating 3 student objects


student1 = Student("0973427", "John", "Smith")

student2 = Student("1882845", "Mary", "Wilson")

student3 = Student("0729032", "Ye", "Yang")

32
Creating Student objects
class Student:

def init (self, id, first_name, last_name):


...

# creating 3 student ob jects


student1 = Student("0973427", "John", "Smith")

student2 = Student("1882845", "Mary", "Wilson")

student3 = Student("0729032", "Ye", "Yang")

33
Accessing object instance attributes
class Student:

def init (self, id, first_name, last_name):


...

# creating 3 student ob jects


student1 = Student("0973427", "John", "Smith")

student2 = Student("1882845", "Mary", "Wilson")

student3 = Student("0729032", "Ye", "Yang")

# get object attributes


print(student1.id)
print(student1.first_name)
print(student1.last_name)
print(student1.username)

34
Accessing class attributes

class Student:

email_domain = "solla.sollew.edu"
student_dir = "/user/student"

# creating 3 student objects


student1 = Student("0973427", "John", "Smith")
student2 = Student("1882845", "Mary", "Wilson")
student3 = Student("0729032", "Ye", "Yang")

# get class attributes


print(Student.email_domain)
print(Student.student_dir)

35
Modify object instance attributes
student2 = Student("1882845", "Mary", "Wilson")

# display object attributes


print("Before: ")
print(student2.id)
print(student2.first_name)
print(student2.last_name)

# change student last name


student2.last_name = "Davis"

# display object attributes after update


print("After: ")
print(student2.id)
print(student2.first_name)
print(student2.last_name)

Before: After:
1882845 1882845
Mary Mary
Wilson Davis 37
Modify class attributes

# change email domain


Student.email_domain = "mail.solla.sollew.edu"

# change student directory


Student.student_dir = "/usr/home/student"

37
Defining an object instance method

class Student:

def fullname(self):
"""
Get student's full name
"""

return self.first_name +
" " + self.last_name

Instance method:
● Automatically pass the object instance (self) as the
first parameter
● May use instance attribute and instance method
38
Defining an object instance method

class Student:

def fullname(self):
"""
Get student's full name
"""

return self.first_name +
" " + self.last_name

# creating a student object


student1 = Student("0973427", "John", "Smith")

# calling method - from the object instance


print(student1.fullname())

39
Defining an object instance method

class Student:

def fullname(self):
return self.first_name + " " + self.last_name

# creating a student object


student2 = Student("1882845", "Mary", "Wilson")

# display object attributes


print("Before: ")
print(student2.fullname()) Before:
Mary Wilson
# change student last name After:
student2.last_name = "Davis" Mary Davis

# display object attributes after update


print("After: ")
print(student2.fullname())
40
Defining an object instance method

class Student:

def email(self):
"""
Get student's email: username@domain
"""
return self.username + "@" +
Student.email_domain

# creating a student object


student2 = Student("1882845", "Mary", "Wilson")

# display email
print(student2.email())

[email protected]

41
Defining an object instance method

class Student:

def email_alias(self):
"""
Get student's friendly-looking email:
firstname.lastname.3IDdigits@domain
"""
return self.first_name + "." + self.last_name + "." +
self.id[0:3] + "@" + Student.email_domain

# creating a student object


student2 = Student("1882845", "Mary", "Wilson")

# display email alias


print(student2.email_alias())

[email protected]

42
Defining an object instance method

class Student:

def home_dir(self):
"""
Get student's Unix home directory:
studentDir/username
"""
return Student.student_dir + "/" +
self.username

# creating a student object


student2 = Student("1882845", "Mary", "Wilson")

# display home directory


print(student2.home_dir())

/user/student/mw188

43
Defining an object instance method

class Student:

def print_detail(self):
print("Student ID: " + self.id)
print("First name: " + self.first_name)
print("Last name: " + self.last_name)
print("Full name: " + self.fullname())
print("Username: " + self.username)
print("Email: " + self.email())
print("Email alias: " + self.email_alias())
print("Home directory: " + self.home_dir())

# creating a student object


student2 = Student("1882845", "Mary", "Wilson")

# display details
student2.print_detail()

44
Defining an object instance method

# creating a student object


student2 = Student("1882845", "Mary", "Wilson")

print("Before:")
student2.print_detail()

# change student last name


student2.last_name = "Davis"

print("After:")
student2.print_detail()

Before:
Student ID: 1882845
First name: Mary
Last name: Wilson
Full name: Mary Wilson
Username: mw188
Email:
[email protected]
Email alias:
Home directory: /user/student/mw188 45
Defining an object instance method

# creating a student object


student2 = Student("1882845", "Mary", "Wilson")

print("Before:")
student2.print_detail()

# change student last name


student2.last_name = "Davis"

print("After:")
student2.print_detail()

After:
Student ID: 1882845
First name: Mary
Last name: Davis
Full name: Mary Davis
Username: mw188
Email:
[email protected]
u
Home directory: /user/student/mw188 46
Thank you!

You might also like