Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

[CreativeProgramming]Lecture11-2_Classes and Inheritance

The document covers key concepts of object-oriented programming including classes, inheritance, encapsulation, and polymorphism. It explains how to access class attributes using getters and setters, and illustrates the creation of derived classes that inherit from base classes. Additionally, it provides examples of method overriding and operator overloading within class hierarchies.

Uploaded by

allrounderguno
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

[CreativeProgramming]Lecture11-2_Classes and Inheritance

The document covers key concepts of object-oriented programming including classes, inheritance, encapsulation, and polymorphism. It explains how to access class attributes using getters and setters, and illustrates the creation of derived classes that inherit from base classes. Additionally, it provides examples of method overriding and operator overloading within class hierarchies.

Uploaded by

allrounderguno
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Creative Programming

Spring 2025
CUL1122 Lecture #11-2
Classes and Inheritance
Today

❖Accessing Class Attributes


▪ Accessors and Mutators (Getters and Setters)
❖Fundamental Concepts of Object-Oriented Programming
▪ 1) Abstraction
▪ 2) Encapsulation
▪ 3) Inheritance
▪ 4) Polymorphism

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

Class Hidden Attributes


Definition and Methods
Visible Methods

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

❖Parent Class (or Base/Superclass)


Animal
❖Child Class (or Derived/Subclass)
▪ By default, inheriting all attributes and
methods from the parent class. Person Cat Rabbit

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

❖Default arguments are used when no value is provided for specified


parameters in a method call.
def set_name(self, newname=""):
self.name = newname
# If no newname value is given, the set_name() method uses ‘’ by default.
a = Animal(3)
a.set_name()
print(a.get_name())
# When set_name() is called with ‘fluffy’ for newname, it uses ‘fluffy’.
a = Animal(3)
a.set_name("fluffy")
print(a.get_name())

16
Default Arguments
❖Example: A function that squares a number when the number of
multiplications is not provided, using a default argument.

No exponent, square instead.

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

❖Adding a unique speak() method to the derived class.


▪ This method is only callable from Cat objects; calling it from Animal objects will
result in an error.
❖Since __init__() is not overridden, code reuse occurs from the base
class, Animal.

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

❖Overloading the + operator for Rabbit objects.


▪ Defining the operation r4 = r1 + r2 for two Rabbit objects, r1 and r2.
▪ Here, r4 becomes a new Rabbit object with parents r1 and r2, aged 0.
def add_ (self, other):
# returning object of same type as this class
return Rabbit(0, self, other)

recall Rabbit’s __init__(self, age, parent1=None, parent2=None)

25
Derived Class: Rabbit

❖Overloading the == operator for Rabbit objects.


▪ This operator is used to check if two Rabbit objects are siblings.
▪ Since Rabbit IDs are unique, comparing IDs determines whether they share the
same parent.

def _eq_ (self, other):


parents_same = self.parent1.rid == other.parent1.rid \
and self.parent2.rid == other.parent2.rid
parents_opposite = self.parent2.rid == other.parent1.rid \
and self.parent1.rid == other.parent2.rid
return parents_same or parents_opposite

26
Lab 11-2: Classes and Inheritance
Exercise #1: Encapsulation

❖Add code to access attributes directly, as well as through a setter


method.

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

You might also like