0% found this document useful (0 votes)
8 views82 pages

Week 10

Object-Oriented Programming (OOP) is a software development paradigm that organizes code into self-contained units called objects, which combine data and behavior. Key concepts include classes, inheritance, encapsulation, and polymorphism, which enhance code organization, reusability, and maintainability. Python implements these principles through specific syntax and conventions, allowing developers to create structured and modular applications.
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)
8 views82 pages

Week 10

Object-Oriented Programming (OOP) is a software development paradigm that organizes code into self-contained units called objects, which combine data and behavior. Key concepts include classes, inheritance, encapsulation, and polymorphism, which enhance code organization, reusability, and maintainability. Python implements these principles through specific syntax and conventions, allowing developers to create structured and modular applications.
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

Object Oriented

Programming:
Classes &
Inheritance
Introduction to Python OOP

Python Team
What is Object Oriented Programming?

Object-Oriented Programming (OOP) is a fundamental

paradigm for software development, modeling real-world

entities.

It revolves around 'objects' which are self-contained units

combining data (attributes) and behavior (methods).


preliminary
Data + Behavior

A core principle: 'everything is an object,' promoting code


OOP groups data and methods into objects, facilitating
organization and reusability.
structured design, code extension, and reuse through a

modular approach.
OOP Concepts in Python

Basic Concepts Advanced Concepts

Class
Encapsulation
A blueprint for creating objects, defining structure and

behavior. Bundling data and methods into a single unit (class),

Object restricting direct external access.

An instance of a class, representing a real-world entity with Inheritance


state and actions.
Mechanism allowing a new class to derive properties and
Attribute
behaviors from an existing class.
Variables that store data or state associated with an object.
Polymorphism
Method

Ability of objects to take on multiple forms, allowing varied


Functions defined within a class that define an object's
method implementations.
behaviors.

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.

Structured Development Modular Components Data Protection


Real Life Example: Objects
In Object-Oriented Programming (OOP), the concept of an 'object' directly mirrors entities from the real world.
These digital objects encapsulate data (attributes) and behavior (methods), much like physical objects.
Understanding this mapping is key to grasping OOP principles.

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

Class build Object directions_car


A blueprint or template that defines the structure and A concrete instance of a class, created based on its

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.

Blueprint Concrete Instance


Defining a Class in Python
What is a Class? Basic Definition Example
check_circle Blueprint for creating objects. class Student:
check_circle Bundles data and functionality into a single pass
unit.
check_circle User-defined template for creating instances. PascalCase Convention
Class names are typically written in PascalCase. Each
The 'class' keyword
word starts with an uppercase letter, e.g., Student ,
It signals the creation of a new class definition. The MyAwesomeClass .
code block following it defines the class's members.
Instantiating Objects
What is Instantiation? Creating Instances in Python
Instantiating an object is the process of
class Student:
creating a concrete instance from a class pass # A blueprint for student objects
blueprint.
# Instantiation: creating an object from the class
Objects are the actual cookies you cut out of student1 = Student()
dough (memory) using cookie cutters (classes).
To verify the object's type:

print(type(student1))

Output: <class '__main__.Student'>

A class can have multiple instances.


The __init__ Method
Special Initialization Method

Code Example: Student Class


The `__init__` method acts as a constructor in Python class Student:
classes. def __init__(self, name):
[Link] = name
It is automatically called whenever a new object
(instance) is created.

Its main role is to initialize the object's attributes,


setting up its initial state.

By assigning initial values, `__init__` ensures that newly


created objects are consistently ready for use.
Constructor Definition

Attribute Initialization
Creating Objects with Attributes

Objects are individual instances created from a


class blueprint.

The __init__ method assigns initial values to an


object's attributes, like 'name'.
student1 = Student("Alice")
print([Link]) # Alice Attributes are accessed via dot notation, e.g.,
'[Link]', to retrieve stored data.

Object Instantiation & Attribute Access


lightbulb
Self Parameter

"The 'self' parameter is crucial for methods


What is 'self'? to interact with the specific instance's data,
In Python, 'self' is the first parameter in instance allowing for distinct object states."

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

"Methods enable objects to interact and modify


their own state."

Code Example
Calling Methods

Methods in Python OOP Syntax & Example


Methods are functions associated with objects. They
[Link]()
encapsulate the behavior and actions an object can

perform, defining how it interacts with its own data.


Output:

Part of a class definition.


Hello, my name is Alice
Operate on instance data ( self ).

Called on specific object instances.


This calls the greet() method belonging to the student1
object, executing the code defined within that method for

student1 .

Key: self refers to the object instance.


More Attributes
Classes can be designed to hold multiple
Adding Multiple Attributes
attributes, allowing objects to store a wider range
of data about themselves. The `__init__` method
class Student:
def __init__(self, name, age): can be extended to accept and assign these
[Link] = name additional properties.
[Link] = age
Expanding an object's definition with more attributes

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:

involves changing the characteristics or properties


[Link] = 21
associated with an object. These attributes define the
print([Link])
object's current state and can be updated as needed.

Output: 21

Attributes of an object, specific to its instance, can be


This code snippet demonstrates how to directly assign a
directly modified to reflect new states or values,
new value to the 'age' attribute of the 'student1' object. The
ensuring dynamic object behavior.
change is immediate and reflects the updated state.
Attribute Scope
Understanding Instance vs. Class Attributes in Python

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.

check_circle Accessed via [Link]. check_circle Accessed [Link].


via

"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

specific object." instance."

Attribute Lookup Order: Instance's Namespace ➔ Class's Namespace.


Class Attribute Example
Defining a Class Attribute Key Characteristics
arrow_right_alt Defined directly within the class, outside of any methods.
class Student: arrow_right_alt Shared by ALL instances (objects) of the class.
school = "ABC University"
arrow_right_alt Accessed using either the class name or any instance of
the class.

group Shared Across All Instances


Accessing Class Attributes
Example:
class Student:
Class attributes are properties that belong to the school = "ABC University"
class itself, rather than to any specific instance of
the class. student1 = Student()

They are shared among all objects (instances)


created from that class. Accessing via Class Name:

Accessing them is straightforward, using dot print([Link]) # Output: ABC


notation through the class name or an instance. University

Shared by all instances Accessing via Instance:

print([Link]) # Output: ABC


University
Encapsulation
Encapsulation bundles data (attributes) and methods into a Python Conventions
single unit, known as a class.

It restricts direct access to internal components, providing a _attribute


controlled interface to interact with an object's state. A convention for weak encapsulation,
indicating an attribute is for internal use. It
This mechanism protects critical data from unintended is still accessible externally.
external changes and promotes organized, secure code
development. __attribute

lock
Triggers name mangling for pseudo-private
access. Harder, but not impossible, to
access externally.
Benefits:

visibility_off Data Hiding


layers Abstraction
shield_lock Code Security & Organization
Private Attributes
Attributes prefixed with double underscores (`__`) are Why Use Private Attributes?
intended as 'private'.
check_circle Encapsulation: Restrict direct external access.
They are primarily for internal class use, though not check_circle Avoid naming conflicts in subclassing.
strictly enforced.
Python's Convention
class Student:
def __init__(self, name): check_circle Uses __attribute (double underscore prefix).
self.__name = name check_circle Not true privacy, but a strong signal for internal use.
Name Mangling Private attributes support encapsulation, ensuring that certain
data is managed and accessed solely within the class's context.
Getter and Setter Methods
In Python, getters and setters are methods used
to access and modify the private attributes of a
class.

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.

A mechanism to create a new class from an existing


Class Hierarchy
one, inheriting its properties and behaviors.
Why Use Inheritance?

sync Code Reusability account_tree Logical Hierarchy


check_circle Reduces duplicate code check_circle Organized code structure
check_circle Common functionality reused check_circle Build class hierarchies
check_circle Easier to maintain check_circle Cleaner, more manageable code
Inheritance allows you to structure your code in a
Common functionality can be reused and extended in hierarchical manner, leading to cleaner and more
different contexts, reducing the need to duplicate code. organized code.
Inheritance Syntax
Python Syntax Example Key Concepts
A child class automatically acquires attributes and methods from
its parent. Inheritance allows a new class to acquire attributes and
methods from an existing class, promoting code reuse.

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.

Here, Student inherits from Person.


subdirectory_arrow_right Enables
OOP.
code reusability and hierarchical structure in
Example: Base (Parent) Class
What is a Base/Parent Class? Python Example: Animal Class
A base class (also known as a parent class or The 'Animal' class below serves as a base class. It
superclass) is an existing class that provides defines a common behavior that can be shared or
features (methods and attributes) to be inherited specialized by its child classes.
by other classes.
class Animal:
The class being inherited from. def speak(self):
Establishes a foundation for related classes. print("Animal speaks")

Promotes code reuse and hierarchy.


Example: Derived (Child) 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

Establishes a hierarchical relationship speak() method is Overridden


Method Overriding Key Characteristics

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

Python Code Output

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.

• Essential for managing multiple inheritance.


Using super() alt_route
Purpose of super() Practical Example
Calls methods from a parent class within a child class.
class Dog(Animal):
Extends and reuses inherited functionality.
def speak(self):
super().speak()
Returns Proxy Object
print("Woof!")

Key Benefits
• Avoids explicit base class naming.
• Simplifies hierarchy changes.
• Supports multiple inheritance.

Calls Animal's `speak` then prints "Woof!"


__init__ in Inheritance

Code Example: Key Concept:


class Person: In inheritance, a child class's `__init__` method must call
def __init__(self, name):
the parent class's `__init__` method using
[Link] = name
super().__init__() . This ensures all inherited
class Student(Person): attributes are properly initialized, maintaining the
def __init__(self, name, id): integrity of the object's state.
super().__init__(name)
[Link] = id

settings Attribute Initialization


MULTI-LEVEL INHERITANCE

Multilevel inheritance forms a chain where a class

inherits from a parent, which in turn inherits from


Animal
another class. A derived class accesses features from

all parent classes in the chain.

class Animal: Mammal


pass

class Mammal(Animal):
pass
Dog
class Dog(Mammal):
pass
Multiple Inheritance

A class can inherit properties and methods Syntax Structure


from more than one parent class.

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

Inherits from A and B


Python MRO (Method Resolution Order)

What is MRO? Determining Method Calls

preliminary Method Resolution Order (MRO) defines the sequence

Python follows to search for a method within a class

hierarchy.
It is the mechanism that determines which specific method

implementation gets invoked when multiple parent classes

define the same method.

MRO is crucial for predictable and consistent method resolution,


How to Inspect MRO:
especially in complex inheritance scenarios.

arrow_right Use [Link]() method

arrow_right Access C.__mro__ attribute

arrow_right Utilize help(C) function


isInstance and isSubclass

isinstance()
person issubclass()
preliminary
Checks whether an object is an instance of a class (or Checks whether one class is a subclass of another

a tuple of classes). class (or a tuple of classes).

Object Type Check Class Hierarchy Check

Example: Example:

isinstance(dog, Dog) issubclass(Dog, Animal)


Practical Example: Shapes

Defining Base Shape Class


OOP in Action

class Shape:
def area(self):
pass

Inheriting and Implementing Rectangle

class Rectangle(Shape):
def __init__(self, w, h):
self.w = w
self.h = h

def area(self): This example showcases inheritance and method

return self.w * self.h overriding to calculate the area of different shapes.


Using the Shapes Example

rect = Rectangle(5, 4)
print([Link]()) # 20

This snippet illustrates a practical application of the `Rectangle` class,

demonstrating object instantiation and method invocation to calculate the

area based on width and height.


Recap & Best Practices

lan Organized & Reusable


Use OOP for organized, reusable code that
call_split Judicious Inheritance
Choose inheritance judiciously to model
structures it logically, enhancing "is-a" relationships clearly and precisely.
maintainability.
Avoid deep, complex hierarchies that
Encapsulates data and behavior for better lead to rigidity.
control.
Prefer composition over inheritance for
Promotes modularity and reusability of "has-a" relationships.
components.
Thank You
Any questions?

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

Problem Statement Solution Code

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.

# Create an instance of the Book class


Key concepts: Class definition, __init__ method, and object book1 = Book("1984", "George Orwell")
instantiation.

# Access the attributes


print([Link]) # Output: 1984
print([Link]) # Output: George Orwell

menu_book
A1: Define a Simple Class (Answer)

What is a Class?

Classes bundle data and functionality. They create new

object types, allowing new instances to be made. Each


class Book:
instance has attributes for its state.
def __init__(self, title, author):
OOP Core
[Link] = title
[Link] = author

The __init__ Method book1 = Book("1984", "George Orwell")

This method acts as a constructor, automatically called


print([Link]) 1984
when a new object is created. It initializes instance
print([Link]) George Orwell
variables like 'title' and 'author'.

Constructor
Exercise 2: Method in Class

Methods in Python

integration_instructions
Classes

Question:

Add a method called description to the Book class which returns a


Methods are functions inside a class,
string in the format: ' <title> written by <author> '.
defining an object's behaviors and

actions. They typically operate on the


instance's data.
Hint:

Define a function inside the class using self . The 'self' Parameter

The self parameter refers to the

instance of the class, allowing methods

to access and modify its attributes and

call other methods.


A2: Method in Class (Answer)
Key Concepts
class Book:
def __init__(self, title, author):
[Link] = title
check_circle Methods define actions objects can
perform.
[Link] = author

def description(self): check_circle They operate on the object's


return f"{[Link]} written by {[Link]}" attributes using 'self'.

# Create an instance of the Book class


book1 = Book("1984", "George Orwell") check_circle Enhance functionality and data
interaction.
# Call the description method and print the result
print([Link]()) # Output: "1984 written by George Orwell"
Methods encapsulate behavior, allowing
objects to perform actions relevant to
their data, making code organized and
reusable.
Exercise 3: Class Attribute

Answer:

Question: class Book:


library = "Central Library"
check_circle Add a class attribute called library to the Book
class with the value 'Central Library'. def __init__(self, title, author):
[Link] = title
check_circle How can each book object access this attribute? [Link] = author

book1 = Book("1984", "George Orwell")


Hint:

Define attributes outside __init__ and access them via Accessing:


[Link] .
print([Link]) Central Library
print([Link]) Central Library
A3: Class Attribute (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.

# They are unique to each instance.


[Link] = title ● Shared by all instances of the class.

[Link] = author
● Accessed using either the class name or an instance.

# Create an instance of Book


book1 = Book("1984", "George Orwell") ● Changes to a class attribute through the class affect all instances.

# Access the class attribute through the instance


print([Link]) In the example, 'library' is a class attribute, common to all
# Output: Central Library 'Book' objects.

# Access the class attribute through the class itself


print([Link])
# Output: Central Library
Exercise 4: Encapsulation

Question: lightbulb Hint:

Make the book's title attribute __ ; define


Prefix with
private.
get_title() and
Write getter and setter methods for it. set_title() methods.
A4: Encapsulation (Answer)

class Book:
def __init__(self, title, author):
self.__title = title
[Link] = author

def get_title(self):
return self.__title

def set_title(self, title):


self.__title = title

book1 = Book("1984", "George Orwell")


print(book1.get_title()) # 1984
book1.set_title("Animal Farm")
print(book1.get_title()) # Animal Farm

Encapsulation protects data via private attributes and public methods.


Exercise 5: Inheritance

Question:
Base Class: Vehicle
Create a base class Vehicle with method move() -

prints 'Vehicle is moving'. class Vehicle:


def move(self):
Create a derived class Car that inherits from print("Vehicle is moving")
Vehicle and overrides move() to print 'Car is moving'.
Instantiate both and show their outputs. Derived Class: Car

class Car(Vehicle):
def move(self):
Hint: print("Car is moving")

Use inheritance and method overriding.


Instantiation & Output

Inheritance Method Overriding # Instantiate Vehicle


my_vehicle = Vehicle()
my_vehicle.move()
# Output: Vehicle 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()

Python Code Explanation

class Vehicle: The super().move() call ensures that the

def move(self): `Vehicle`'s `move` method is executed first,


print("Vehicle is moving") demonstrating method overriding with parent

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 Vehicle: Output:


def move(self): Vehicle is moving
print("Vehicle is moving") Car is moving

class Car(Vehicle):
def move(self):
super().move()
print("Car is moving")

mycar = Car()
[Link]()
Exercise 7: Constructor in Inheritance

Concept Overview Solution Code


Define a base class `Person` with a `name` attribute.
class Person:
Create a derived class `Teacher` that inherits from def __init__(self, name):
`Person` and adds a `subject` attribute. [Link] = name

Use the parent constructor to initialize the `name` class Teacher(Person):


attribute from the child class. def __init__(self, name, subject):
super().__init__(name)
[Link] = subject

key super().__init__() is key!


t = Teacher('Bob', 'Math')
print([Link])
print([Link])

The `super().__init__()` method is crucial for calling Output:


the parent class's constructor, ensuring proper Bob
initialization of inherited attributes. Math
A7: Constructor in Inheritance (Answer)

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)

Python Code Output & Explanation

class A: Output:

def hello(self):
print("Hello from A") "Hello from A"

class B: Python's Method Resolution Order (MRO) determines the


def hello(self): method call hierarchy for multiple inheritance.
print("Hello from B")
It follows a Depth-First, then Left-to-Right search. In C(A,
class C(A, B): B), class A is listed first.
pass
Therefore, hello() from class A is found and executed
obj = C()
first.
[Link]()

MRO: Class A takes precedence


A8: Multiple Inheritance (Answer)
Understanding MRO
class A: In multiple inheritance, Python uses the Method
Resolution Order (MRO) to determine which
def hello(self):
method to call when there's a name conflict.
print("Hello from A")
Method Resolution Order (MRO)
class B:
def hello(self): For the class `C(A, B)`, the MRO prioritizes classes
print("Hello from B") from left to right. Therefore, `A` is checked before
`B`. As a result, `[Link]()` executes the method
from class `A`.
class C(A, B):
pass Output: Hello from A

obj = C()
[Link]()
Exercise 9: isinstance and issubclass

Context & Question Solution & Explanation


Recall classes A, B, C defined as class C(A, B): pass
# obj = C()
from Exercise 8. print(isinstance(obj, C)) # True
Given obj = C() , evaluate the following statements: print(isinstance(obj, A)) # True
print(issubclass(C, B)) # True
isinstance(obj, C)

isinstance(obj, A) The evaluation results are:


issubclass(C, B) check_circle instance of class C. is True because is a direct
isinstance(obj, C) obj

Hint: check_circle from A, making isanTrue


isinstance(obj, A)
obj
because class C inherits
instance of A as well.
Use Python's built-in isinstance and issubclass
functions.
check_circle explicitly defined tois inherit
issubclass(C, B) True because class C is
from class B.
A9: `isinstance` and `issubclass` (Answer)

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:

Create a base class Animal with method speak() - just prints

'Some sound'.

Create a child class Dog that overrides speak() and prints

'Bark!'.

Instantiate both and show their outputs.

KEY CONCEPT

Hint: Method overriding. Method overriding enables subclasses to offer

specialized behavior for methods inherited from

their parent classes.


A10: Practice - Zoo (Answer)

class Animal:
def speak(self):
print("Some sound")

class Dog(Animal):
def speak(self):
print("Bark!")

a = Animal()
d = Dog()

[Link]() # Output: Some sound


[Link]() # Output: Bark!

Contact: your_email@[Link]
Introduction to
Programming
(Python)
Multiple Choice Questions:
Object-Oriented Programming

group Python Team


Question 1: The 'self' keyword

In Python, the self keyword is a convention


What does the self keyword that represents the instance of the class. It is
represent in a class method? the first argument in any instance method,
referring to the specific object calling that
a) The class itself method and enabling access to its attributes
and methods.
b) The parent class

c) The object calling the Correct


method

d) A local variable
Question 2: The __init__ method

Q2. What is the role of the Understanding `__init__`


`__init__` method in a Python
class? The `__init__` method is a special method known as
the constructor, automatically called when a new
class instance is created.
a) It destroys objects
b) It serializes objects Initializes new objects
c) It initializes new objects Sets up initial state

d) It inherits attributes Assigns values to attributes

Answer: c) It initializes new objects


rocket_launch Essential for creating well-structured and
functional Python classes.
Question 3: Defining a Class

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.

a) function To create a class in Python, the `class` keyword is used,

lightbulb
followed by the class name.

b) class
Answer: b) class

c) def

d) new
Question 4: Creating an Instance

Which of the following correctly creates an instance of a class called


Understanding Instance

Cat ? Creation

In Python, an instance is created by

a) Cat = object() directly calling the class name, similar to

a function call.

b) mycat = new Cat() This action triggers the __init__


method to set up the object's initial state

and attributes.
c) mycat = Cat() Correct

An instance is a unique, concrete object

created from a class, which acts as a


d) mycat = Cat blueprint.
Question 5: Inheritance in Python

What does inheritance allow you to


do in Python?
account_tree Key Concept: Python
Inheritance

Inheritance enables creating a new class (child)


a) Include code from another file based on an existing one (parent), inheriting its
attributes and methods. This promotes code reuse
b) Define variables and models 'is-a' relationships.

c) Create a new class based on an


existing class

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

individual instances. They are declared within the class scope,

a) They are defined inside methods outside any method.

b) They are shared among all instances


A core feature is that they are shared across all instances

(objects) of that class. Changes to a class variable affect every


c) They can only be strings
instance.
d) They are private by default

Answer: b) They are shared among all instances


Class variables are designed for data common to all

objects, ensuring consistency across all instances of a


share
class.
Question 8: Method Overriding

Q8. What does method overriding mean? Correct Answer

a) Changing variable values c) Replacing a parent class method in a child class

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

class, modifying or extending its behavior.


c) Replacing a parent class method in a child class

d) Calling different methods from the same class


Question 9
Key Functionality
The `super()` function
The `super()` function calls methods from a

parent class within a child class. It helps to

extend or override inherited methods while


What does the `super()` function do?
reusing parent functionality.

a. Returns the main class

b. Calls a method from the parent class Why Use `super()`?

c. Creates a new object


No need to hardcode parent class names.

d. Deletes objects

Useful when class hierarchies change.

Returns a proxy object representing the

parent's class.
Answer:

b) Calls a method from the parent class


Essential for cooperative multiple inheritance.
Correct
Encapsulation is a fundamental concept in Object-

Oriented Programming (OOP) that restricts direct

access to some of an object's components, making

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.

a) Prefixing with capital letter


Correct Answer:

b) Prefixing with one underscore _


c) Prefixing with two underscores __
c) Prefixing with two underscores __

d) Suffixing with exclamation mark ! Notice

A single underscore _ conventionally signals an

attribute for internal use, but it remains directly

accessible.
Question 11: Code Output Example 1

Q11. What output will this code give?

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

Multiple Inheritance Explained


Q12. How many base classes can a Python
In Python, a class can inherit properties and methods from
class inherit from?
more than one parent (base) class. This is a fundamental

feature of the language, offering flexibility in code design.


a. One

b. Two "When a class is derived from more than one base class it is called

multiple Inheritance."
c. Three

d. Any number

check_circle Answer: d) Any number

account_tree
Question 13: isinstance() function

Q13. What does the isinstance(obj, Class) What isinstance() Does:


function check?
The isinstance() function returns True if the specified

object is an instance of the specified class or a subclass


a) If obj is a variable
thereof; otherwise, it returns False.
b) If obj is an instance of Class
c) If Class inherits from obj Key Features:

Type checking for objects.


d) If obj is private
Considers subclass relationships.

Answer: b) If obj is an instance of Class Aids in robust code design.

Signature:
Correct Answer
isinstance(object, classinfo)

isinstance() vs type() :
type() which checks for an exact type match,
Unlike

isinstance() is more versatile as it also accounts for


inheritance (subclass relationships).
Question 14: Code Output Example 2

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

c) That method cannot be called provided by its parent class.

d) Python will stop


Default Inheritance

Method overriding allows for specialized behavior, but

in its absence, the base class functionality persists.


Answer: b) The parent’s method is used
Question 16: Method Resolution Order (MRO)

What is method resolution order (MRO)? What is MRO?

a) The order of arguments in a method


Method Resolution Order (MRO) defines the search

check_circle b) The order in which Python looks for a called

method in the hierarchy


sequence for attributes and methods in an inheritance

hierarchy, especially crucial in multiple inheritance

scenarios.
c) The order in which data is stored in memory

d) The order methods are defined


It resolves conflicts when names collide, utilizing the C3

linearization algorithm in Python.

Answer: b) hub
Question 17: issubclass() function

Q17. Which of the following correctly Understanding


checks if Dog is a subclass of Animal ? issubclass()
The built-in issubclass() function
a) [Link](Animal) checks if a given class is a subclass
b) isSubclass(Dog, Animal) of another class, returning True or
False .
c) issubclass(Dog, Animal)
Syntax:
d) issubclass(Animal, Dog)
issubclass(class, classinfo)
Answer: c) issubclass(Dog, Animal)
Example: issubclass(Dog, Animal)
Question 18: Object String Representation data_object
Q18. Which method name is a Python Understanding __str__ & __repr__
“magic method” for object string
representation? Python's 'dunder methods' (double underscore) define how

objects convert to strings. These are crucial for clarity in

debugging and user output.


a) init
__str__() : Human-readable for users (e.g., used by
b) str
print() ).
c) get __repr__() : Developer-centric for debugging (e.g.,
d) call shown in the interpreter).

Both __str__ and __repr__ provide valuable insights into

object states, making Python code more maintainable and

easier to debug.

Answer: b) str Correct


Dunder Methods
Question 19: Encapsulation

Which of the following best describes


encapsulation?

a) Sharing all attributes

b) Restricting access to some of an object's components What is Encapsulation?

c) Creating instances
Encapsulation means bundling data and methods within a

d) Defining global variables class, controlling external access to its internal state.

It restricts direct access to components, providing a controlled

lock
interface to protect important data from accidental changes.

Answer: b) Restricting access to some of an object's

components
Question 20: Code Output Example 3

Q20. What is printed?

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

print("Hello from B")

In Python's multiple inheritance, the Method Resolution Order


class C(A, B):
(MRO) determines the search order for methods. For C(A, B) ,
pass
the MRO is C -> A -> B . Thus, the hello() method from

class A is found and executed first.


x = C()
[Link]()

You might also like