Object Oriented Programming (Simple Activities)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

Laboratory Activity 1(Midterm)

PYTHON’S OBJECT-ORIENTED
PROGRAMMING

LEARNING EXPECTATIONS
✓ Students must understand how to construct and use object and class in Python.
✓ Students must understand how the different important parts (attributes, method,
etc.) in creating a class in Python.
✓ Students must know what and how to create a class out of another class in
Python.

EXERCISE 3.1
Create a Bus child class that inherits from the Vehicle class. The default fare
charge of any vehicle is seating capacity * 100. If Vehicle is Bus instance, we need
to add an extra 10% on full fare as a maintenance charge. So total fare for bus
instance will become the final amount
= total fare + 10% of the total fare.

Note: The bus seating capacity is 50. So, the final fare amount should be 5500. You
need to override the fare() method of a Vehicle class in Bus class.

Use the following code for your parent Vehicle class. We need to access the
parent class from inside a method of a child class.

PASTE THE SOURCE CODE AND OUTPUT HERE


EXERCISE 3.2
Create a Bus class that inherits from the Vehicle class. Give the capacity
argument of Bus.seating_capacity() a default value of 50.

Use the following code for your parent Vehicle class. You need to use method overriding.

PASTE THE SOURCE CODE AND OUTPUT HERE


MACHINE PROBLEM
1. Rock, Paper, Scissors
Write a program to play a three-game match of “rock, paper, scissors” between
a person and a computer. The program should use a class named Contestant
having two subclasses named Human and Computer. After the person makes
his or her choice, the computer should make its choice at random. The
Contestant class should have instance variables for name and score. (Note:
Rock beats scissors, scissors beat paper, and paper beats rock.)

The program should have an output like this:

PASTE THE SOURCE CODE AND OUTPUT HERE

import random

class Player:
def __init__(self, name):
self.name = name
self.choice = None
self.score = 0

def get_choice(self, choice):


self.choice = choice

def add_and_update_score(self):
self.score += 1

def rock_paper_scissors():
human_player = Player(input('Enter name of human: '))
computer_player = Player(input('Enter name of computer: '))

human_wins = [('rock', 'scissors'), ('paper', 'rock'), ('scissors',


'paper')]

while (human_player.score < 3) and (computer_player.score < 3):


while True:
human_choice = input(f'{human_player.name}, enter your choice: ')
if human_choice.lower() in ['rock', 'paper', 'scissors']:
human_player.get_choice(human_choice.lower())
break
else:
print(f'"{human_choice}" in invalid. Choose only from "rock",
"paper", and "scissors."')

computer_choice = random.choice(['rock', 'paper', 'scissors'])


computer_player.get_choice(computer_choice)
print(f'{computer_player.name} chooses {computer_player.choice}')

player_choices = (human_player.choice, computer_player.choice)

if human_player.choice == computer_player.choice:
pass
elif player_choices in human_wins:
human_player.add_and_update_score()
else:
computer_player.add_and_update_score()

print(f'{human_player.name}: {human_player.score}
{computer_player.name}: {computer_player.score}')

if human_player.score == 3:
print(f'{human_player.name.upper()} WINS')
else:
print(f'{computer_player.name.upper()} WINS')

if __name__ == '__main__':
rock_paper_scissors()
ANSWER THE FOLLOWING QUESTIONS
• Define object and class in Python.

In Python, an object is simply a collection of data (variables) and methods


(functions) [1]. It is an instance of a class [2]. Objects are created using a class as a
blueprint or prototype [3]. They have their own unique properties and behaviors.
On the other hand, a class is like a blueprint or constructor for creating
objects [4]. It defines the structure and behavior that objects of that class will have [3].
Classes provide a way to bundle data and functionality together [3]. Python classes
have all the standard features of Object-Oriented Programming, such as inheritance
and the ability to create derived classes [5].
In summary, a class is a blueprint for creating objects, while an object is an
instance of a class that has its own properties and methods [1][2].

• Differentiate instance from instance variable.

In Python, an instance refers to a specific object or occurrence of a class. It


can have its own unique set of attributes and methods. On the other hand, an instance
variable is a variable that is specific to each instance of a class. It holds different values
for each object or instance of the class. Instance variables are owned by objects and
allow for individual customization of their values [6]. Overall, the main difference is that
an instance is an object of a class, while an instance variable is a variable specific to
each instance of the class [7].

• Define the meaning of inheritance in Python.

In Python, inheritance refers to the capability of one class to derive or


inherit the properties and methods from another class. It establishes an "is-a"
relationship between two classes, where the child class inherits the attributes and
behaviors of the parent class [8][9]. This allows the child class to access and utilize
all the data members and functions defined in the parent class [10]. Python supports
multiple inheritance, which means a class can derive from multiple parent classes
[11]. It is a fundamental concept in object-oriented programming that promotes code
reuse and modularity [12].

• Define the meaning of instantiation in Python.

Instantiation in Python refers to the process of creating an instance or


object of a class. Instantiating a class, means creating a new instance that inherits
all the variables and methods defined in the class [13]. This process involves calling
the class constructor, which triggers the instance creator .__new__() to create a
new empty object [14]. The attributes of the class are then used to initialize the
object, using the unique values provided [15]. In simpler terms, instantiation is the
act of creating an object from a class [16].
REFLECTION

Write a reflection about Python’s Object-Oriented Programming.

Pythons Object Oriented Programming (OOP) plays a role, in the language’s success and
broad acceptance in the programming world. It is a paradigm that emphasizes structuring code,
into objects which are simply instances of classes. These objects encompass both data and
behavior contributing to Pythons adaptability and ability to express ideas effectively.

The Python OOP has four basic principles for writing clean and concise code. These are
Abstraction, Encapsulation, Inheritance, and Polymorphism. First, Abstraction is the process of
shielding the user from the code's inner workings. This keeps the code simple and makes sure
we just pay attention to what matters. In Python’s OOP, abstraction is accomplished by
developing implementation classes (subclasses) and interface classes (base classes). Then,
Encapsulation is the process of enclosing data and its processes in a 'capsule' or unit so that it
cannot be accessed or changed outside of that unit, making the data private. Making variables
inside of a class private does this. Furthermore, Inheritance is what helps in writing a reusable
and more concise code. A parent class and a child class exist in inheritance. The methods and
properties of the parent class are inherited by the child class. This feature skyrockets the code’s
reusability. Lastly, simply put, polymorphism means "many forms." This means that one function
or object in Python can be utilized in a variety of ways or data types. In OOP, polymorphism may
be implemented with inheritance through method overriding. Polymorphism is useful if
modification is needed for the parent method to fit the needs of the child class while still allowing
access to the parent class method.

In summary, Python’s Object Oriented Programming (OOP) is a strong aspect of the


language. It strikes a balance, between simplicity, readability and versatility. Whether you're
working on scripts or large-scale applications, Pythons OOP capabilities offer a great foundation
for software development. It encourages coding best practices and promotes modularity, which
makes it a great choice for both beginners and experienced programmers. However, like with any
tool it's important to use Python OOP while following the best practices and design patterns to
help you fully leverage its potential while avoiding any problem.
References

[1] “Python Classes and Objects [With Examples],” Programiz.com, 2019.


https://www.programiz.com/python-programming/class

[2] Vishal, “Classes and Objects in Python,” PYnative, Aug. 25, 2021.
https://pynative.com/python-classes-and-objects/

[3] “Python Classes and Objects,” GeeksforGeeks, Oct. 15, 2019.


https://www.geeksforgeeks.org/python-classes-and-objects/

[4] W3Schools, “Python Classes,” W3schools.com, 2019.


https://www.w3schools.com/python/python_classes.asp

[5] “9. Classes — Python 3.8.4rc1 documentation,” docs.python.org.


https://docs.python.org/3/tutorial/classes.html

[6] “Object Oriented Programming in Pyth: Class and Instance Variables,” DigitalOcean.
https://www.digitalocean.com/community/tutorials/understanding-class-and-instance-variables-
in-python-3

[7] “Class Variables vs Instance Variables in Python,” Atatus Blog - For DevOps Engineers,
Web App Developers and Server Admins., Feb. 17, 2023. https://www.atatus.com/blog/class-
variables-vs-instance-variables-in-java/

[8] “Inheritance in Python,” GeeksforGeeks, Aug. 31, 2018.


https://www.geeksforgeeks.org/inheritance-in-python/

[9] “Python Inheritance (With Examples),” www.programiz.com.


https://www.programiz.com/python-programming/inheritance

[10] “Inheritance in Python - javatpoint,” www.javatpoint.com.


https://www.javatpoint.com/inheritance-in-python

[11] R. Python, “Inheritance and Composition: A Python OOP Guide – Real Python,”
realpython.com. https://realpython.com/inheritance-composition-python/

[12] Vishal, “Inheritance in Python,” PYnative, Mar. 18, 2021. https://pynative.com/python-


inheritance/

[13] “Explain Inheritance vs Instantiation for Python classes.,” www.tutorialspoint.com.


https://www.tutorialspoint.com/Explain-Inheritance-vs-Instantiation-for-Python-classes
(accessed Oct. 19, 2023).

[14] R. Python, “Python Class Constructors: Control Your Object Instantiation – Real
Python,” realpython.com. https://realpython.com/python-class-constructor/

[15] “What does instantiate mean in the context of this lesson?,” Codecademy Forums, Jan.
08, 2020. https://discuss.codecademy.com/t/what-does-instantiate-mean-in-the-context-of-this-
lesson/465216 (accessed Oct. 19, 2023).
[16] “What is instantiate in Python?,” Quora, 2019. https://www.quora.com/What-is-
instantiate-in-Python (accessed Oct. 19, 2023).

You might also like