Week 10
Week 10
Programming:
Classes &
Inheritance
Introduction to Python OOP
Python Team
What is Object Oriented Programming?
entities.
modular approach.
OOP Concepts in Python
Class
Encapsulation
A blueprint for creating objects, defining structure and
OOP organizes code with objects and classes, enhancing modularity, reusability, and scalability.
settings
Why Use OOP?
preliminary
Code Organization
preliminary
Reusability
lock
Encapsulation
OOP structures complex programs Classes and objects can be reused Encapsulation bundles data and
into smaller, manageable, logical across different parts of an methods into objects, hiding
units (objects). This results in application or in new projects, internal details and protecting
clearer, more maintainable reducing development time and data integrity. This promotes
codebases. effort. modularity.
directions_car
Attributes:
Car Object school Student Object
Attributes:
Make, Model, Color, Year Name, Student ID, Major
Speed, Fuel Level GPA, Courses Enrolled
Behaviors: Behaviors:
Start Engine, Stop Engine Enroll Course, Study
Accelerate, Brake, Turn Submit Assignment, Get Grades
Class and Object Definitions
behavior for a set of objects. blueprint. Each object has its own unique state.
It specifies the attributes (data) and methods (functions) that Objects possess specific values for their attributes and can
objects of this class will possess. execute the methods defined by their class.
print(type(student1))
Attribute Initialization
Creating Objects with Attributes
view_in_ar
methods, serving as a direct reference to the current
object (instance) itself.
Instance Reference
Accesses and modifies object attributes.
Ensures object independence.
Automatically passed when method is called.
A widely accepted naming convention.
Adding Methods
What is a Method?
Defining a Method
Methods are functions defined inside a class,
representing the actions an object can perform.
class Student:
def __init__(self, name):
[Link] = name
• Behavior of objects
def greet(self):
• Operates on instance data
print("Hello, my name is", [Link])
• Defined with ' self ' as first parameter
Code Example
Calling Methods
student1 .
settings_applications
enhances its ability to represent complex real-world
entities with richer data.
Modifying Attributes
In Object-Oriented Programming, modifying attributes Assume `student1` object exists with an 'age' attribute:
Output: 21
Instance Attributes
check_circle Unique to each object.
person Class Attributes
check_circle
group
Shared by all instances of a class.
check_circle Defined within __init__usingself.attribute. check_circle Defined directly within the class body.
"When an instance attribute shares a name with a class "If modified directly on an instance, a new instance attribute is
attribute, the instance attribute takes precedence for that created, effectively 'shadowing' the class attribute for that
lock
Triggers name mangling for pseudo-private
access. Harder, but not impossible, to
access externally.
Benefits:
These methods provide controlled access to Example: Managing the __name attribute
attributes, ensuring data integrity.
def get_name(self):
Python uses naming conventions like return self.__name
__attribute for private intent, not strict access
modifiers.
def set_name(self, name):
self.__name = name
Encapsulation
lock
Summary: Classes
Blueprint Attributes
A class acts as a blueprint or a template for These are variables within a class that hold data,
creating objects, defining their structure and representing the characteristics or properties of an
behavior. object.
Methods Encapsulation
Functions defined inside a class that specify the The bundling of data and methods into a single unit
actions or behaviors an object can perform. (class) to hide internal state and restrict access.
What is Inheritance?
account_tree
In Object-Oriented Programming (OOP),
inheritance is a core principle. It allows for
the creation of a hierarchy among classes,
promoting code reuse and logical structure.
class Person:
pass subdirectory_arrow_right Parent Class (Base/Superclass): The class providing
common features.
class Student(Person):
pass subdirectory_arrow_right Child Class (Derived/Subclass): A class that extends or
specializes a parent class.
A derived class (or child class) extends an existing base class Python Example:
(parent class), inheriting its characteristics. This promotes class Dog(Animal):
code reuse and establishes an "is-a" relationship. def speak(self):
print("Woof!")
Inherits from a base class
Can extend or override methods Dog is a Derived Class of Animal
alt_route Child class redefines a parent method check_circle Same name, parameters, and return type as
parent method.
Method overriding allows a subclass to provide its check_circle When called via a child object, Python
executes the child's specific implementation.
own specific implementation for a method that is
already defined in its super-class.
check_circle Improves code flexibility, reusability, and
maintainability.
When a method in a child class has the identical
signature to one in its parent, the child's version
takes precedence.
check_circle Apolymorphism.
fundamental concept in achieving run-time
Overriding Example
cat = Animal()
dog = Dog()
[Link]()
# Animal speaks
[Link]()
# Woof!
Method overriding allows a child class to provide a specific implementation for a method already defined in its
parent class.
The super() Function
Concept: Call Parent Class Methods Example: __init__ in Inheritance
Access methods from a parent (superclass) inside a
child (subclass). class Person:
def __init__(self, name):
[Link] = name
class Student(Person):
Why Use super()? def __init__(self, name, id):
super().__init__(name)
• Avoids hardcoding parent class names. [Link] = id
• Maintains flexibility in class hierarchies.
Key Benefits
• Avoids explicit base class naming.
• Simplifies hierarchy changes.
• Supports multiple inheritance.
class Mammal(Animal):
pass
Dog
class Dog(Mammal):
pass
Multiple Inheritance
class A:
This allows the derived class to combine pass
functionalities from multiple sources.
class B:
Example: A 'Bat' class can inherit from both pass
'Mammal' and 'WingedAnimal'.
class C(A, B):
hub
pass
hierarchy.
It is the mechanism that determines which specific method
isinstance()
person issubclass()
preliminary
Checks whether an object is an instance of a class (or Checks whether one class is a subclass of another
Example: Example:
class Shape:
def area(self):
pass
class Rectangle(Shape):
def __init__(self, w, h):
self.w = w
self.h = h
rect = Rectangle(5, 4)
print([Link]()) # 20
your_university_email@[Link]
contact_support
Introduction to Programming
with Python: Exercises
Object-Oriented Programming Exercises
Python Team
Exercise 1: Define a Simple Class
Answer
Create a class called Book with two attributes: title and class Book:
author (both strings). def __init__(self, title, author):
[Link] = title
Create an object for the book '1984' by 'George Orwell'.
[Link] = author
Hint: Use the __init__ method to initialize attributes.
menu_book
A1: Define a Simple Class (Answer)
What is a Class?
Constructor
Exercise 2: Method in Class
Methods in Python
integration_instructions
Classes
Question:
Define a function inside the class using self . The 'self' Parameter
Answer:
class Book:
# This is a class attribute.
# It's shared by all instances of the Book class.
library = "Central Library"
What are Class Attributes?
def __init__(self, title, author):
# These are instance attributes. ● Defined directly within the class, outside of any method.
[Link] = author
● Accessed using either the class name or an instance.
class Book:
def __init__(self, title, author):
self.__title = title
[Link] = author
def get_title(self):
return self.__title
Question:
Base Class: Vehicle
Create a base class Vehicle with method move() -
class Car(Vehicle):
def move(self):
Hint: print("Car is moving")
# Instantiate Car
my_car = Car()
my_car.move()
# Output: Car is moving
A5: Inheritance (Answer)
class Vehicle:
def move(self):
print("Vehicle is moving")
class Car(Vehicle):
def move(self):
print("Car is moving")
mycar = Car()
[Link]() # Output: Car is moving
code Exercise 6: Using super()
functionality reuse.
class Car(Vehicle):
def move(self):
super().move() Output
print("Car is moving")
Vehicle is moving
mycar = Car() Car is moving
[Link]()
A6: Using super() (Answer)
class Car(Vehicle):
def move(self):
super().move()
print("Car is moving")
mycar = Car()
[Link]()
Exercise 7: Constructor in Inheritance
class Person:
def __init__(self, name):
[Link] = name
class Teacher(Person):
def __init__(self, name, subject):
super().__init__(name)
[Link] = subject
t = Teacher('Bob', 'Math')
print([Link]) Bob
print([Link]) Math
A8: Multiple Inheritance (Answer)
class A: Output:
def hello(self):
print("Hello from A") "Hello from A"
obj = C()
[Link]()
Exercise 9: isinstance and issubclass
obj = C()
print(isinstance(obj, C)) # True
print(isinstance(obj, A)) # True
print(issubclass(C, B)) # True
(Note: C inherits from B through multiple inheritance from the previous question (Q8), making issubclass(C,
B) True)
Exercise 10: Practice - Zoo
Question:
'Some sound'.
'Bark!'.
KEY CONCEPT
class Animal:
def speak(self):
print("Some sound")
class Dog(Animal):
def speak(self):
print("Bark!")
a = Animal()
d = Dog()
Contact: your_email@[Link]
Introduction to
Programming
(Python)
Multiple Choice Questions:
Object-Oriented Programming
d) A local variable
Question 2: The __init__ method
Q3. Which symbol is used to A class in Python acts as a blueprint for creating
objects, defining their attributes and methods. It is
define a class in Python?
fundamental to object-oriented programming.
lightbulb
followed by the class name.
b) class
Answer: b) class
c) def
d) new
Question 4: Creating an Instance
Cat ? Creation
a function call.
and attributes.
c) mycat = Cat() Correct
d) Hide methods
check_circle Answer: c
OOP Fundamental
Question 6: Parent Class Understanding Inheritance
Identification
A parent class is the class being inherited
If class B inherits from class A, which is the from, also called the base class. A child
account_tree
parent class? class is the class that inherits from another
class, also known as the derived class.
a) A
b) B
c) Both
d) None
Answer: a) A
Understanding Class Variables
Question 7: Class Variables
Which statement about class variables is true? Class variables are attributes belonging to the class itself, not
b) Defining multiple methods of the same name in Method overriding allows a subclass to provide a specific
different classes implementation for a method already defined in its parent
d. Deletes objects
parent's class.
Answer:
Question 10: Private variables accessible only within the class itself.
Attributes
In Python, attributes prefixed with two underscores __
undergo name mangling, making them harder to
Which of the following makes an attribute
access directly. This mechanism helps enforce
private in Python?
encapsulation.
accessible.
Question 11: Code Output Example 1
class A:
def show(self): a) A
print("A")
b) B
class B(A):
pass c) Error
d) Nothing
b = B()
[Link]()
Answer: a) A
Question 12: Multiple Inheritance
b. Two "When a class is derived from more than one base class it is called
multiple Inheritance."
c. Three
d. Any number
account_tree
Question 13: isinstance() function
Signature:
Correct Answer
isinstance(object, classinfo)
isinstance() vs type() :
type() which checks for an exact type match,
Unlike
Options:
Q14. What is the output?
a) ABC
class X:
school = "ABC"
b) XYZ
a = X()
b = X()
[Link] = "XYZ" c) Error
print([Link])
d) None
Answer:
a) ABC
Question 15: Un-overridden Methods
account_tree
What happens if a child class does not override a
method from its parent?
a) Error is raised
If a child class does not override a method, it
b) The parent’s method is used
naturally inherits and utilizes the implementation
scenarios.
c) The order in which data is stored in memory
Answer: b) hub
Question 17: issubclass() function
easier to debug.
c) Creating instances
Encapsulation means bundling data and methods within a
d) Defining global variables class, controlling external access to its internal state.
lock
interface to protect important data from accidental changes.
components
Question 20: Code Output Example 3
Hello from B
Hello from C
class A:
def hello(self): Hello from A
print("Hello from A")
Error
class B:
def hello(self): Answer: c) Hello from A