[CreativeProgramming]Lecture11-2_Classes and Inheritance
[CreativeProgramming]Lecture11-2_Classes and Inheritance
Spring 2025
CUL1122 Lecture #11-2
Classes and Inheritance
Today
3
Accessing Class Attributes
❖When accessing class attributes from outside the class, utilize getter
and setter methods for clarity.
class Animal(object):
def init (self, age):
self.age = age
self.name = None
def get_age(self):
return self.age
def get_name(self):
return self.name
def set_age(self, newage):
self.age = newage
def set_name(self, newname=""):
self.name = newname
def str (self):
return "Animal:"+str(self.name)+":"+str(self.age)
4
Object-Oriented Concept 1: Abstraction
❖Representing an entity involves extracting its attributes and behaviors.
❖For instance, in developing a program to calculate shipping fees, you
would extract the following attributes and behaviors:
▪ Attributes: cost_per_pound, weight
▪ Behaviors: calc_shipping_cost()
❖For example, a “parcel box” can be abstracted to a “shipping box” class.
Attributes class ShippingBox:
Sender’s name def __init__(self, …)
Receiver’s name self.sender = …
Weight self.receiver = …
Cost of shipping per pound self.weight = …
Behaviors def calc_shipping_cost(self):
Calculate shipping cost pass
5
Object-Oriented Concept 2: Encapsulation
❖Encapsulation defines an object’s properties and behaviors within a
single class, restricting external access to specific attributes or methods.
❖When defining a class, certain attributes or methods can be marked as
private, making them accessible only within the class (a concept known
as Information Hiding).
Visible Attributes
6
Object-Oriented Concept 2: Encapsulation
❖To expose only the necessary attributes and methods required for using
the class externally.
❖For instance, only the method name of calc_shipping_cost() needs to be
public, without revealing its internal implementation.
getWeight()
sender
receiver
getSender() getReceiver()
shipping_cost_per_pound
weight
calc_shipping_cost()
7
Object-Oriented Concept 2: Encapsulation
❖Hidden attributes are accessible only through getters and setters.
❖Internal changes are permitted freely, while malicious external
alterations are prevented.
class Animal(object):
def init (self, age):
self.years = age
def get_age(self):
return self.years
8
Hierarchies
Image Credits, clockwise from top: Image Courtesy Deeeep, CC-BY-NC. Image Image Courtesy MTSOfan, CC-BY-NC-SA. Image Courtesy Carlos Solana,
license CC-BY-NC-SA. Image Courtesy Rosemarie Banghart-Kovic, license CC-BY-NC-SA. Image Courtesy Paul Reynolds, license CC-BY. Image Courtesy 9
Kenny Louie, License CC-BY. Courtesy Harald Wehner, in the public Domain.
Hierarchies
Student
10
Object-Oriented Concept 3: Inheritance
❖Inheritance involves creating derived classes from a base class.
▪ Derived classes reuse code from the base class.
▪ They inherently include all its attributes and methods, so only additional
attributes and methods need to be added.
❖Derived classes can be extended in two primary ways:
▪ 1) Adding new attributes or methods
▪ 2) Overriding existing attributes or methods
11
Object-Oriented Concept 3: Inheritance
❖Developing individual classes often leads to duplicating attributes or
methods.
BankAccount CheckingAccount SavingsAccount
holder holder holder
account_type account_type account_type
balance balance balance
deposit() deposit() deposit()
withdraw() withdraw() withdraw()
overdraft_fee interest_rate
process_deposit() calc_interest()
12
Object-Oriented Concept 3: Inheritance
❖Code reuse is achieved through derived classes.
BankAccount
holder
account_type
balance
deposit()
withdraw()
CheckingAccount SavingsAccount
overdraft_fee interest_rate
process_deposit() calc_interest()
13
Object-Oriented Concept 4: Polymorphism
❖Overloading: Methods with the same name are invoked based on their
parameters.
❖For operators, the method is determined by the data type (e.g., integers,
floats, strings).
14
Object-Oriented Concept 4: Polymorphism
❖Overriding: Redefining base class methods in derived classes.
▪ Example: Redefining sound() in the Dog and Cat classes derived from Animal.
15
Default Arguments
16
Default Arguments
❖Example: A function that squares a number when the number of
multiplications is not provided, using a default argument.
17
Inheritance Example: Animal Base Class
class Animal(object):
def _ init _(self, age):
self.age = age
self.name = None
def get_age(self):
return self.age
def get_name(self):
return self.name
def set_age(self,newage):
self.age = newage
def set_name(self,newname=""):
self.name = newname
def str (self):
return "Animal:"+str(self.name)+":"+str(self.age)
18
Derived Class: Cat
class Cat(Animal):
def speak(self):
print("Meow!")
def str (self):
return "Cat:"+str(self.name)+":"+str(self.age)
19
Which Class’s Method is Used?
❖When both base and derived classes have a method with the same
name, the method is searched for in the derived class during invocation.
❖If not found, the first method encountered as the hierarchy is traversed
upwards will be used for the operation.
20
Derived Class: Person
class Person(Animal):
def init (self, name, age):
Animal. _init (self, age)
self.set_name(name)
self.friends = []
def get_friends(self):
return self.friends
def add_friend(self, fname):
if fname not in self.friends:
self.friends.append(fname)
def speak(self):
print("Hello!")
def age_diff(self, other):
diff = self.age - other.age
print(abs(diff), "year difference")
def str (self):
return "Person:"+str(self.name)+":"+str(self.age) 21
Derived Class: Student
import random
class Student(Person):
def init (self, name, age, major=None):
Person. init (self, name, age)
self.major = major
def change_major(self, major):
self.major = major
def speak(self):
r = random.random()
if r < 0.25:
print("I have homework.")
elif 0.25 <= r < 0.5:
print("I need sleep.")
elif 0.5 <= r < 0.75:
print("I should eat.")
else:
print("I am watching Netflix.")
def str (self):
return "Student:"+str(self.name)+":"+str(self.age)+":"+str(self.major) 22
Derived Class: Rabbit
❖Class variables are shared among all class instances, unlike instance
variables.
❖Example: Using the class variable tag to assign unique IDs to Rabbit
objects.
class Rabbit(Animal):
tag = 1
def __init__(self, age, parent1=None, parent2=None):
Animal.__init__(self, age)
self.parent1 = parent1
self.parent2 = parent2
self.rid = Rabbit.tag
Rabbit.tag += 1
23
Derived Class: Rabbit
class Rabbit(Animal):
tag = 1
def __init__(self, age, parent1=None, parent2=None):
Animal.__init__(self, age)
self.parent1 = parent1
self.parent2 = parent2
self.rid = Rabbit.tag
Rabbit.tag += 1
def get_rid(self):
return str(self.rid).zfill(3)
def get_parent1(self):
return self.parent1
def get_parent2(self):
return self.parent2
24
Derived Class: Rabit
25
Derived Class: Rabbit
26
Lab 11-2: Classes and Inheritance
Exercise #1: Encapsulation
28
Exercise #2: Defining the Person Class
❖Create a Person class that is derived from the Animal class, and explore
the following:
▪ 1) Add attributes and methods for adding friends and retrieving the friend list.
➢Modify the __init__() method and include getter and setter methods for managing the
friend list.
▪ 2) Add more than two friends and retrieve the list of friends.
▪ 3) Add a speak() method that reflects the actions of a Person, such as saying
“Hello!”, and override the __str__() method.
29
Exercise #2: Defining the Person Class
30
Exercise #3: Defining the Student Class
❖Derive a Student class from the Person class and explore the following:
▪ 1) Add a major attribute and implement getter and setter methods for this
attribute.
▪ 2) Call the speak() method to observe the result, then override the method and
call it again.
31
Exercise #3: Defining the Student Class
32
Exercise #3: Defining the Student Class
33
수고하셨습니다!
34