Week3-Python OOP TA
Week3-Python OOP TA
Content
Class
- A class is a template for objects
VariableName1 Type - An object is an instance of a class
VariableName2 Type - Class specific what data its object will have and
VariableName3 Type what behaviour will they exhibit
VariableName4 Type
- Object contians its own value
Instantiate - Instantiate assign value to data member (attributes)
Classes Objects
https://pynative.com/python-encapsulation/
Review: Python Object Oriented Programming
Data Encapsulation
Information hiding: hide object’s internal
representation from the outside
https://pynative.com/python-encapsulation/
Review: Python Object Oriented Programming
Data Encapsulation
Python policy: we are all responsible adults
=> Concentrate on debugging (make everything public)
Public
data1
data1
method1 naming prefix with “_” : non public
method1
convention prefix with “__”: name mangling
Ex:
Protected __data1 => _<NameClass>__data1
_data2
data2
_method2
method2
=> user of the class will respect the convetion and
Public documentation
__data3
data3
__method3
method3
Data hiding: base on the provided getter and setter methods, it is not neccessary to
know the internal running inside of object
Aesthetics: Bundling data and methods within a class makes code more readable
and maintainable
Review: Python Object Oriented Programming
Data Abstraction
- Data abstraction refers to the process of representing essential features without including background details or explanations.
- Abstraction is an OOP concept that focuses only on relevant data of an object.
- It hides the background details and emphasizes the essential data points for reducing the complexity and increase efficiency
- Abstraction method mainly focusses on the idea instead of actual functioning
Parameter Abstraction Encapsulation
Use for Abstraction solves the problem and issues Encapsulation solves the problem and
that arise at the design stage. issue that arise at the implementation
stage.
Focus Abstraction allows you to focus on what Encapsulation enables you to hide the
the object does instead of how it does it code and data into a single unit to secure
the data from the outside world.
Implementation You can use abstraction using Abstract You can implement encapsulation using
Class. Access Modifiers (Public, Protected & https://www.guru99.com/dif
Private.) ference-between-
abstraction-and-
encapsulation.html
Focuses Focus mainly on what should be done. Focus primarily on how it should be done.
Abstraction Encapsulation
Abstraction in Object Oriented Encapsulation solves it implementation
Programming solves the issues at the level.
design level.
Abstraction in Programming is about Encapsulation means binding the code
hiding unwanted details while showing and data into a single unit.
most essential information.
Data Abstraction in Java allows Encapsulation means hiding the internal
focussing on what the information object details or mechanics of how an object
must contain does something for security reasons.
https://www.guru99.co
m/java-data-
abstraction.html
Review: Python Object Oriented Programming
Multilevel Inheritance
Inheritance
Single Inheritance Base Class
- Base class (parent): the class which is inherited from another class
- Derived class (child): the class inherits from another class Base Class
- Inheritance: the action that derived class inherit (public and protected)
attrtibutes and methods from base class. Derived class can overriding Derived Class
methods of base class
- The relationship between base class and derived class is is-a relationship
=> reusability of code: use existing class to create a new class Derived Class
Derived Class
Hybrid Inheritance
Polymorphism in Python
string
length of string
list
len() number of elements
dict
number of keys
- Provide the operators with a special - Derived class inherits from base class, and
meaning for a data type modifies a certain method of base class
Review: Python Object Oriented Programming
Aggregation and Composition
Composition Aggregation
- Composition: One class (container) contain and use other class (content class) as a
data type. If the class (container) is destroyed the content is also destroyed.
- Aggregation: There are not any objects or classes owns another object. It just
creates a reference. If the container is destroy, the content still exists.
Content
- name: string
- identity: int
- price: float
- location: string
- manufacturer: Manufacturer
- 2 public methods
+ __init__(identity, location) + Initialization method: nhận 2 arguments (identity và location)
+ describe(): void + describe() method: print các thông tin của instance (value )
Device Class
Device
- 3 private attributes
+ name kiểu int
- name: string
+ price kiểu string
- price: float + manufacturer instance của Manufacturer class
- manufacturer: Manufacturer
- 2 public methods
+ __init__(name, price, identity, location) + Initialization method: nhận 4 arguments (name, price, identity
+ describe(): void và location)
+ describe() method: print các thông tin của instance (value )
Manufacturer Class
Manufacturer
- 2 private attributes
- identity: int + identity kiểu int
- location: string + location kiểu string
- 2 public methods
+ __init__(identity, location) + Initialization method: nhận 2 arguments (identity và location)
+ describe(): void + describe() method: print các thông tin của instance (value )
CLASS Devcie
INIT FUNCTION __init__(identity, location)
PRIVATE __identity = identity
PRIVATE __location = location
ENDFUNCTION
CLASS Devcie
INIT FUNCTION __init__(name, price, identity, location)
Aggregation in PRIVATE __name = name
OOPS PRIVATE __price = price
PRIVATE __manufacturer = Manufacturer(identity, location)
ENDFUNCTION
- (a) Thực hiện các class student, doctor, và teacher theo mô tả trên. Thực hiện describe() method để print ra tất
cả thông tin của các objects.
- (b) Viết addPerson(person) method trong Ward class để add thêm một người mới với nghề nghiệp bất kỳ
(student, teacher, doctor) vào danh sách người của ward. Tạo ra một ward object, và thêm vào 1 student, 2
teacher, và 2 doctor. Thực hiện describe() method để in ra tên ward (name) và toàn bộ thông tin của từng người
trong ward.
- (d) Viết sortAge() method để sort mọi người trong ward theo tuổi của họ với thứ tự tăng dần. (hint: Có thể sử
dụng sort của list hoặc viết thêm function đều được)
- (e) Viết aveTeacherYearOfBirth() method để tính trung bình năm sinh của các teachers trong ward.
aa
Một Ward gồm có name (string) và danh sách của mọi người trong Ward. Một người person có thể là
student, doctor, hoặc teacher. Một student gồm có name, yob (int) (năm sinh), và grade (string). Một teacher
gồm có name, yob, và subject (string). Một doctor gồm có name, yob, và specialist (string). Lưu ý cần sử
dụng a list để chứa danh sách của mọi người trong Ward.
Perpson
Ward
- name: string
- listPeople: list() Student Doctor Teacher
+ ???
name name name
is-a
realationship Perpson
Ward
- name: string
- listPeople: list() Student Doctor Teacher
+ ???
name name name
Đặc trưng của
mỗi class
Giống nhau cho 3 class yob yob yob
Student, Doctor và Teacher
=> Person cũng có thể có name và yob
grad specialist subject
=> Kế thừa từ Person
Một Ward gồm có name (string) và danh sách của mọi người trong Ward. Một người person có thể là
student, doctor, hoặc teacher. Một student gồm có name, yob (int) (năm sinh), và grade (string). Một teacher
gồm có name, yob, và subject (string). Một doctor gồm có name, yob, và specialist (string). Lưu ý cần sử
dụng a list để chứa danh sách của mọi người trong Ward.
Person
# name: string
Ward # yob: int
- name: string + ???
- listPeople: list()
is-a
+ ???
Student Doctor Teacher
- grade: string - specialist: string - subject: string
- (a) Thực hiện các class student, doctor, và teacher theo mô tả trên. Thực hiện describe() method để print ra tất
cả thông tin của các objects.
Một Ward gồm có name (string) và danh sách của mọi người trong Ward. Một người person có thể là
student, doctor, hoặc teacher. Một student gồm có name, yob (int) (năm sinh), và grade (string). Một teacher
gồm có name, yob, và subject (string). Một doctor gồm có name, yob, và specialist (string). Lưu ý cần sử
dụng a list để chứa danh sách của mọi người trong Ward.
- (a) Thực hiện các class student, doctor, và teacher theo mô tả trên. Thực hiện describe() method để print ra tất
cả thông tin của các objects.
Person
- name: string
- yob: int
+ describe(): void
is-a
ENDCLASS
- (c) Viết countDoctor() method để đếm số lượng doctor trong ward.
Ward
- name: string
- listPeople: list()
+ __init__(name)
+ addPerson(Person): void
+ describe(): void
+ countDoctor(): int
+ sortAge(): void
- (d) Viết sortAge() method để sort mọi người trong ward theo tuổi của họ với thứ tự tăng dần. (hint: Có thể sử
dụng sort của list hoặc viết thêm function đều được)
Person
PUBLIC FUNCTION getYoB()
# name: string
RETURN _yob
# yob: int ENDFUNCTION
+ getYoB(): int
Ward
- name: string PUBLIC FUNCTION sortAge()
- listPeople: list() GET yob of each person in __listPeople
+ __init__(name) SORT yob of each person in __listPeople in descending order
ENDFUNCTION
+ addPerson(Person): void
+ describe(): void
+ countDoctor(): int
+ sortAge(): void
- (e) Viết aveTeacherYearOfBirth() method để tính trung bình năm sinh của các teachers trong ward.
Person
# name: string
# yob: int
+ getYoB(): int
Non-Primitive Stack:
- Pre-defined capacity, can store the elements of a limited size.
- An ordered list (order in which the data arrives is important)
- Insertion and Deletion are done at one end called top.
User-Defined - Top pointer (top) pointing to the topmost element of the stack
- The last element inserted is the first one to be deleted. Last in First out (LIFO) principle
Stack Operations:
- Push(value): insert data onto stack
Linear - Pop(): remove and return the last inserted element from the stack
Auxiliary stack operations:
- Top(): return the last inserted element (top) without removing it
- IsEmpty(): indicate whether the stack is empty or not
Stack Queue - IsFull(): indicate whether the stack is full or not
Stack
Stack Exceptions:
- Overflow: Try to push an element to a full stack
TOP
10 - Underflow: Try to pop out an empty stack
12
31
Review: Python Data Structures
Capacity = 4 Stack Operations:
TOP - Push(value): insert data onto stack
20 - Pop(): remove and return the last inserted element from the stack
TOP
10 10 Auxiliary stack operations:
- Top(): return the last inserted element (top) without removing it
12 12 - IsEmp(): indicate whether the stack is empty or not
- IsFull(): indicate whether the stack is full or not
31 31
Emtpy Stack Top() = 10 Full Stack
TOP 20 10
20
TOP TOP
TOP
10 10 10
TOP
12 12 12 12 12
TOP
31 31 31 31 31 31
Push(31) Push(12) Push(10) Push(20) Pop() Pop()
Stack Exceptions:
Review: Python Data Structures - Overflow: Try to push an element to a full stack
- Underflow: Try to pop out an empty stack
Capacity = 4
TOP TOP
20 20
TOP
10 10 10
Underflow Overflow
12 12 12
31 31 31
Emtpy Stack Top() = 10 Full Stack Pop() Push(20)
TOP 20 10
20
TOP TOP
TOP
10 10 10
TOP
12 12 12 12 12
TOP
31 31 31 31 31 31
Push(31) Push(12) Push(10) Push(20) Pop() Pop()
Thực hiện xây dựng class Stack với các chức năng (method) sau đây
• initialization method nhận một input "capacity": dùng để khởi tạo stack với
capacity là số lượng element mà stack có thể chứa
• .isEmpty(): kiểm tra stack có đang rỗng
• .isFull(): kiểm tra stack đã full chưa
• .pop(): loại bỏ top element và trả về giá trị đó
• .push(value) add thêm value vào trong stack
• .top() lấy giá trị top element hiện tại của stack, nhưng không loại bỏ giá trị đó
• Không cần thiết phải thực hiện với pointer như trong hình minh họa
Stack
Thực hiện xây dựng class Stack với các chức năng (method) sau đây
- capacity: int • initialization method nhận một input "capacity": dùng để khởi tạo stack với
- stack: list() capacity là số lượng element mà stack có thể chứa
+ __init__(capacity) • .isEmpty(): kiểm tra stack có đang rỗng
+ isEmpty(): bool • .isFull(): kiểm tra stack đã full chưa
+ isFull(): bool • .pop(): loại bỏ top element và trả về giá trị đó
+ pop(): any • .push(value) add thêm value vào trong stack
+ push(value): void • .top() lấy giá trị top element hiện tại của stack, nhưng không loại bỏ giá trị đó
+ top(): any • Không cần thiết phải thực hiện với pointer như trong hình minh họa
CLASS Stack PUBLIC FUNCTION push(value)
INIT FUNCTION __init__(capacity) IF isFull()
PRIVATE __capacity = capacity RAISE EXCEPTION(“Overflow”)
PRIVATE __stack = list() ENDIF
Stack ENDFUNCTION __stack.append(value)
ENDFUNCTION
- capacity: int PUBLIC FUNCTION isEmpty()
- stack: list() RETURN len(__stack) == 0 PUBLIC top()
+ __init__(capacity) ENDFUNCTION IF isEmpty()
+ isEmpty(): bool PRINT(“Stack is empty”)
PUBLIC FUNCTION isFull() RETURN
+ isFull(): bool
RETURN len(__stack) == __capacity ENDIF
+ pop(): any
ENDFUNCTION RETURN __stack.[-1]
+ push(value): void ENDFUNCTION
+ top(): any PUBLIC FUNCTION pop()
IF isEmpty() ENDCLASS
RAISE EXCEPTION(“Underflow”)
ENDIF
RETURN __stack.pop()
ENDFUNCTION
...
Content
Non-Primitive Queue:
- Pre-defined capacity, can store the elements of a limited size.
- An ordered list (order in which the data arrives is important)
- Insertions are done at one end (rear)
User-Defined - Deletions are done at other end (front)
- Rear pointer (rear) pointing to the last element of the queue
- Front pointer (front) pointing to the first element of the queue
- The first element inserted is the first one to be deleted. Frist in First out (FIFO) principle
Linear Queue Operations:
- Enqueue(value): insert data onto queue
- Dequeue(): remove and return the first inserted element from the queue
Auxiliary stack operations:
Stack Queue - Front(): return the first inserted element (front) without removing it
- IsEmptyQueue(): indicate whether the queue is empty or not
- IsFullQueue(): indicate whether the queue is full or not
-1 0 1 2 3
Queue Exceptions:
31 12 10 20 - Overflow: Try to enqueue an element to a full queue
- Underflow: Try to dequeue an empty queue
Queue
Review: Python Data Structures
Capacity = 4 Queue Operations:
-1 0 1 2 3
- Enqueue(value): insert data onto queue
Front Pointer - Dequeue(): remove and return the first inserted element from the
queue
Rear Pointer Empty Queue
Auxiliary stack operations:
-1 0 1 2 3 - Front(): return the first inserted element (front) without removing it
- IsEmptyQueue(): indicate whether the queue is empty or not
31 12 10 20 - IsFullQueue(): indicate whether the queue is full or not
Full Queue
-1 0 1 2 3 -1 0 1 2 3 -1 0 1 2 3
31 31 12 10 31 12 10 20
Enqueue(31) Enqueue(10) Dequeue()
⋯
-1 0 1 2 3 -1 0 1 2 3 -1 0 1 2 3
31 12 31 12 10 20 20
Enqueue(12) Enqueue(20) Dequeue()
Queue Exceptions:
Review: Python Data Structures - Overflow: Try to enqueue an element to a full queue
- Underflow: Try to dequeue an empty queue
Capacity = 4
-1 0 1 2 3 -1 0 1 2 3
Underflow
Front Pointer
Rear Pointer Empty Queue Dequeue()
-1 0 1 2 3 -1 0 1 2 3
31 12 10 20 31 12 10 20 Overflow
Full Queue Enqueue(10)
-1 0 1 2 3 -1 0 1 2 3 -1 0 1 2 3
31 31 12 10 31 12 10 20
Enqueue(31) Enqueue(10) Dequeue()
⋯
-1 0 1 2 3 -1 0 1 2 3 -1 0 1 2 3
31 12 31 12 10 20 20
Enqueue(12) Enqueue(20) Dequeue()
Thực hiện xây dựng class Queue với các chức năng (method) sau đây
• initialization method nhận một input "capacity": dùng để khởi tạo queue với capacity là
số lượng element mà queue có thể chứa
• .isEmpty(): kiểm tra queue có đang rỗng
• .isFull(): kiểm tra queue đã full chưa
• .dequeue(): loại bỏ first element và trả về giá trị đó
• .enqueue(value) add thêm value vào trong queue
• .front() lấy giá trị first element hiện tại của queue, nhưng không loại bỏ giá trị đó
• Không cần thiết phải thực hiện với các pointers như trong hình minh họa
Queue
Thực hiện xây dựng class Queue với các chức năng (method) sau đây
- capacity: int • initialization method nhận một input "capacity": dùng để khởi tạo queue với capacity là
- queue: list() số lượng element mà queue có thể chứa
+ __init__(capacity) • .isEmpty(): kiểm tra queue có đang rỗng
• .isFull(): kiểm tra queue đã full chưa
+ isEmpty(): bool
• .dequeue(): loại bỏ first element và trả về giá trị đó
+ isFull(): bool • .enqueue(value) add thêm value vào trong queue
+ dequeue(): any • .front() lấy giá trị first element hiện tại của queue, nhưng không loại bỏ giá trị đó
+ enqueue(value): void • Không cần thiết phải thực hiện với các pointers như trong hình minh họa
+ front(): any
CLASS Queue PUBLIC FUNCTION enqueue(value)
INIT FUNCTION __init__(capacity) IF isFull()
PRIVATE __capacity = capacity RAISE EXCEPTION(“Overflow”)
PRIVATE __queue = list() ENDIF
ENDFUNCTION __queue.append(value)
Queue ENDFUNCTION
PUBLIC FUNCTION isEmpty()
- capacity: int
RETURN len(__queue ) == 0 PUBLIC front()
- queue: list() ENDFUNCTION IF isEmpty()
+ __init__(capacity) PRINT(“Queue is empty”)
+ isEmpty(): bool PUBLIC FUNCTION isFull() RETURN
+ isFull(): bool RETURN len(__queue ) == __capacity ENDIF
+ dequeue(): any ENDFUNCTION RETURN __stack.[0]
ENDFUNCTION
+ enqueue(value): void
PUBLIC FUNCTION dequeue()
+ front(): any IF isEmpty() ENDCLASS
RAISE EXCEPTION(“Underflow”)
ENDIF
RETURN __queue.pop(0)
ENDFUNCTION
...