HCI 9. Object Oriented Programming
Uploaded by adrianwang2003 · 28 May 2024
Preview
Text from the first pagesHwa Chong Institution H2 Computing 1 9 Object Oriented Programming Learning Outcome 9.1 Procedural and Object-Oriented Programming 9.1.1 Procedural Programming : Writing programs made of functions that perform specific tasks - Procedures typically operate on data items that are separate from the procedures - Data items commonly passed from one procedure to another - Focus: to create procedures that operate on the program’s data 9.1.2 Object-Oriented Programming : focused on creating objects Object: entity that contains data and procedures - Data is known as data attributes and procedures are known as methods - Methods perform operations on the data attributes Encapsulation: combining data and procedure into a single object Fundamentals of Object-Oriented Programming Define and understand classes and objects Understand encapsulation and how classes support information hiding and implementation independence Understand inheritance and how it promotes software reuse Understand polymorphism and how it enables code generalisation. Exclude: method overloading and multiple inheritance
Hwa Chong Institution H2 Computing 2 Data hiding: object’s data attributes are hidden from code outside the object and access is restricted to the object’s methods - Protects from accidental corruption - Outside code does not need to know internal structure of the object An Everyday Example of an Object - Data attributes: define the state of an object o Example: clock object would have second, minute, and hour data attributes - Public methods: allow external code to manipulate the object o Example: set_time, set_alarm_time - Private methods: used for object’s inner workings 9.2 Class vs Instance/Object Class: code that specifies the data attributes and methods of a particular type of object o Similar to a blueprint of a house or a cookie cutter Instance: an object created from a class o Similar to a specific house built according to the blueprint or a specific cookie o There can be many instances of one class The housefly and mosquito objects are instances of the Insect class
Hwa Chong Institution H2 Computing 3 9.3 Class Definitions set of statements that define a class’s methods and data attributes - Format: begin with class Class_name: o Class names often start with uppercase letter - Method definition like any other python function definition o self parameter: required in every method in the class – references the specific object that the method is working on 9.3.1 Initializer Method Also called class’s constructor, this method automatically executed when an instance of the class is created - Initializes object’s data attributes and assigns self parameter to the object - Format: def __init__ (self): - Usually the first method in a class definition (coin.py) import random # The Coin class simulates a coin that can be flipped. class Coin: # initializes the sideup data attribute with 'Heads'. def __init__(self): self.sideup = 'Heads' # The toss method generates a random number in the range of 0 # to 1. If the number is 0, then sideup is set to 'Heads'. # Otherwise, sideup is set to 'Tails'. def toss(self): if random.randint(0, 1) == 0: self.sideup = 'Heads' else: self.sideup = 'Tails' 9.3.2 Creating an Instance - To create a new instance of a class call the initializer method o Format: My_instance = Class_Name() - To call any of the class methods using the created instance, use dot notation o Format: My_instance.method() o Because the self parameter references the specific instance of the object, the method will affect this instance, reference to self is passed automatically
Hwa Chong Institution H2 Computing 4 # The main function. def main(): # Create an object from the Coin class. my_coin = Coin() # Display the side of the coin that is facing up print ('This side is up:', my_coin.sideup) # Toss the coin. print ('I am going to toss the coin ten times:') for count in range(10): my_coin.toss() print (my_coin.sideup) # Call the main function. main() Actions caused by the Coin() expression The my_coin variable references a Coin object 9.3.3 Data Hiding Hiding Attributes An object’s data attributes should be private. In Python, a nam e prefixed with an underscore (e.g. _spam) is a commonly used convention to denote a private attribute or method.
Hwa Chong Institution H2 Computing 5 Accessor and Mutator Methods All of a class’s data attributes are private and provide methods to access and change them. - Accessor/Getter methods: return a value from a class’s attribute without changing it o Safe way for code outside the class to retrieve the value of attributes - Mutator/Setter methods: store or change the value of a data attribute Storing Classes in Modules Classes can be stored in modules - Filename for module must end in .py - Module can be imported to programs that use the class The BankAccount Class Class methods can have multiple parameters in addition to self – For __init__, parameters needed to create an instance of the class o Example: a BankAccount object is created with a balance o When called, the initializer method receives a value to be assigned to the _balance attribute – For other methods, parameters needed to perform required task o Example: deposit method amount to be deposited (account.py) # The BankAccount class simulates a bank account. class BankAccount: # The __init__ method accepts an argument for the account's # balance. It is assigned to the _balance attribute. def __init__(self, bal): self._balance = bal # The deposit method makes a deposit into the account. def deposit(self, amount): self._balance += amount # The withdraw method withdraws an amount from the account. def withdraw(self, amount): if self._balance >= amount: self._balance -= amount else: print ('Error: Insufficient funds') # The get_balance method returns the account balance. def get_balance(self): return self._balance
Hwa Chong Institution H2 Computing 6 (account_test.py) # This program demonstrates the BankAccount class. import account def main(): # Get the starting balance. start_bal = float(input('Enter your starting balance: ')) # Create a BankAccount object. savings = account.BankAccount(start_bal) # Deposit the user's paycheck. pay = float(input('How much were you paid this week? ')) print('I will deposit that into your account.') savings.deposit(pay) # Display the balance. print('Your account balance is ${savings.get_balance():.2f}.') # Get the amount to withdraw. cash = int(input('How much would you like to withdraw? ')) print('I will withdraw that from your account.') savings.withdraw(cash) # Display the balance. print(f'Your account balance is${savings.get_balance():.2f}.') # Call the main function. main() The __str__ method - Object’s state: the values of the object’s attribute at a given moment - __str__ method: displays the object’s state o Automatically called when you pass the object’s name to the print statement o Automatically called when the object is passed as an argument to the str function # The __str__ method returns a string indicating the object's state. def __str__(self): state_string = f'Your account balance is ${self._balance:.2f}.' return state_string # Display the balance. print(savings)
Hwa Chong Institution H2 Computing 7 9.4 Working With Instances - Instance attribute: belongs to a specific instance of a class o Created when a method uses the self parameter to create an attribute - If many instances of a class are created, each would have its own set of attributes (simulation.py) import random # The Coin class simulates a coin that can be flipped.
Content continues in the PDF. Download PDF
Related notes
- NYJC 2026 Prelim P2Exam Papers · 2026
- NYJC 2026 Prelim P1Exam Papers · 2026
- DHS 2026 Y6 H2 Computing Prelim Paper 2_finalExam Papers · 2026
- ACJC 2026 JC2 Computing Prelim Paper 2 (Practical)Exam Papers · 2026
- 2026_NJC Prelim_Computing_P2.pdfExam Papers · 2026
- 2026_JPJC_Computing_Prelim_P2_finalExam Papers · 2026
- 2026_JPJC_Computing_Prelim_P1_markschemeExam Papers · 2026
- 2026_JPJC_Computing_Prelim_P1_finalExam Papers · 2026
- 2026 ACJC Prelim Computing Paper 2Exam Papers · 2026
- 2024 ACJC Computing PromoExam Papers · 2024
- 2023 ACJC Promo QPExam Papers · 2023
- 2022 ACJC Computing Promo Paper 2Exam Papers · 2022
- See all H2 Computing notes

