- 1. BASIC:
- 2. Inheritance: inherit all attributes and method from parent class
- 1. super()
- 2. explicitly call parent's constructor - 3. Polymorphism: override parent's method
- 1. super() - 5. overload
- 6. containment
1. BASIC:
-
instantiation of object and use of object to use method
-
initialised to zero don't need to include in parameter list within()
moneyIn is initialized to zero inside the constructor because:
- It always starts at zero in any new vending machine.
- There is no reason to ask the user to specify this initial value.
- This design choice simplifies the interface and ensures consistency.
- declare as array/list
items is a list, dont need to pass as parameter
The reason whyitemsdoes not need to be passed as a parameter to the__init__method lies in the purpose of the__init__method and the internal logic of how the__itemslist is created and managed. Here's a detailed explanation:
1. What the Constructor Does
The constructor (__init__) is responsible for initializing the attributes of a class when an object is created. In this case:
- The
__itemslist is a private attribute meant to store the vending machine's food items. - Instead of requiring the user to pass a complete list of items, the constructor takes individual items (
item1,item2,item3,item4) as parameters and then internally creates the__itemslist.
---
2. Why Not Pass items Directly?
If items (a pre-constructed list) were passed as a parameter, the user would have to create and format the list themselves before creating the object. For example:
python
CopyEdit
# If items were passed as a parameter items = ["Chips", "Chocolate", "Soda", "Cookies"] vending_machine = VendingMachine(items)
While this is possible, it makes the interface less user-friendly:
- The user now has to know that the vending machine requires exactly 4 items.
- They must pre-format a list, which adds extra complexity.
Instead, by requiring item1, item2, item3, and item4 as separate parameters, the class handles the creation of the list internally, simplifying usage:
python
CopyEdit
# Simplified interface vending_machine = VendingMachine("Chips", "Chocolate", "Soda", "Cookies")
This approach reduces the burden on the user and hides implementation details (e.g., that items are stored in a list).
3. Encapsulation
Encapsulation is a core principle of object-oriented programming:
- Internal details of how data is stored (
__itemsas a list) should be hidden from the user. - By requiring individual items as parameters, the class controls how those items are stored and ensures the list is always created correctly (e.g., exactly 4 items).
This approach ensures that:
- Users cannot accidentally pass an improperly formatted list (e.g., one with fewer or more than 4 items).
- The class internally enforces the correct structure of its attributes.
4. Design Philosophy
This design follows the principle of clean and simple interfaces:
- Users of the class shouldn't have to worry about its internal implementation (e.g., that the items are stored in a list).
- By requiring individual items, the class abstracts away the details, making it easier and more intuitive for the user to create a vending machine.
5. What If You Did Pass items as a Parameter?
If the constructor were designed to take items as a parameter, you could simplify its implementation, but you'd lose some benefits of encapsulation and usability. For example:
python
CopyEdit
class VendingMachine:
def init(self, items): if len(items) != 4: raise ValueError("Vending machine must have exactly 4 items.") self.__items = items self.__moneyIn = 0.0`
While this works, it:
- Requires the user to manage the list formatting.
- Reduces the control the class has over ensuring valid data.
6. Conclusion
items does not need to be passed directly to the constructor because:
-
The constructor is designed to handle the creation of the
__itemslist internally. -
Users only need to pass individual items (
item1,item2,item3,item4), making the class easier and more intuitive to use. -
Encapsulation ensures that the class maintains control over how its attributes are initialized and structured.
-
append list
-
pseudocode declaration of data type
PRIVATE Attribute Name: Data Type
PUBLIC PROCEDURE NEW(attribute1: Data Type, attribute2: Data Type)
#oop
class ClassName:
def __init__(self, param1,param2):
self.__attribute1=param1
self.__attribute2=param2
def get_method(self):
return self.attribute1
def set_method(self,change1):
self.__attribute1=change1
class vendingMachine:
def __init__(self,item1,item2,item3,item4):
#PRIVATE items:ARRAY:[0:3] OF foodItem
#PRIVATE moneyIn: REAL
self.__items=[]#items parameter no need to declared in parameter list
self.__items.append(item1)
self.__items.append(item2)
self.__items.append(item3)
self.__items.append(item4)
self.__moneyIn=0.0
2. Inheritance: inherit all attributes and method from parent class
class Vehicle:
def __init__(self, brand, year):
self._brand = brand
self._year = year
1. super()
- subclass/ child class definition
class Car(Vehicle):
1. constructor definition with all parameter( parents & child parameter)
```python
def __init__(self, brand, year, model, fuel_type):
- super() constructor to call parents constructor
super().__init__(brand, year) #parent parameter without self
class Car(Vehicle):
def __init__(self, brand, year, model, fuel_type):
super().__init__(brand, year) # Call parent constructor
self._model = model # additional own parameter
self._fuel_type = fuel_type
2. explicitly call parent's constructor
class Child(Parent):
def__init__(self,a, b, c, d, e):
Parent.__init__(self,a, b, c)#call parent's constructor with self
self.__durian=d
self.__epal=e
meaning can use parent's attribute in child class
access parent's class attribute in Child class
#instantiate object
node=Node(10)
#use getter
leftPointer=node.GetLeft()
rightPointer=node.GetRight()
data=node.GetData()
#use setter
node.SetData(20) #modify data
node.SetLeft(5)
node.SetRight(15)
if NewNode.GetData()<self.__Tree[NodeAccess].GetData():
NodeAccess=self.__Tree[NodeAccess].GetLeft()
name mangling
node=Node(10)
lefPointer=node._Node__LeftPointer
rightPointer=node._Node__RightPointer
data=node._Node__Data
node._Node__Data=20
node._Node__LeftPointer=5
node._Node__RightPointer=15
if NewNode._Node__Data<self.__Tree[NodeAcess]._Node__Data:
NodeAccess = self.__Tree[NodeAccess]._Node__LeftPointer
directly instantiate parent's object inside child class
class TreeClass(Node):
def __init__(self):
self.__FirstNode = -1
self.__NumberNodes = 0
self.__Tree = [] # Create an empty list
for _ in range(20):
self.__Tree.append(Node(-1)) # Instantiate 20 Nodes
3. Polymorphism: override parent's method
class Vehicle:
def __init__(self, brand, year):
self._brand = brand
self._year = year
def show_details(self):
print(f"Brand: {self._brand}")
print(f"Year: {self._year}")
1. super()
super().method_name() #call parent's method name
class Car(Vehicle):
def __init__(self, brand, year, model, fuel_type):
super().__init__(brand, year) # Call parent constructor
self._model = model # additional own parameter
self._fuel_type = fuel_type
def show_details(self): # Overriding the method
print("Car Details:")
super().show_details() # Call parent method
print(f"Model: {self._model}")
print(f"Fuel Type: {self._fuel_type}")
Output:
# Create instances
v = Vehicle("Generic Motors", 2010)
c = Car("Toyota", 2022, "Corolla", "Petrol")
# Demonstrating polymorphism
print("Vehicle Object:")
v.show_details()
print("\nCar Object:")
c.show_details()
# output
Vehicle Object:
Brand: Generic Motors
Year: 2010
Car Object:
Car Details:
Brand: Toyota
Year: 2022
Model: Corolla
Fuel Type: Petrol
5. overload
ability of a function or method to behave differently based on the number or type of arguments passed to it.
class Vehicle:
def __init__(self, name=None):
if name is not None:
self.name = name
else:
self.name = "Unnamed Vehicle"
def start(self, sound=None):
if sound is not None:
print(f"{self.name} starts with sound: {sound}")
else:
print(f"{self.name} starts silently.")
Usage:
v1 = Vehicle()
v1.start() # Unnamed Vehicle starts silently.
v2 = Vehicle("Truck")
v2.start("Vroom!") # Truck starts with sound: Vroom!
6. containment
class Vehicle:
def __init__(self, brand, year):
self._brand = brand
self._year = year
def show_details(self):
print(f"Brand: {self._brand}, Year: {self._year}")
class Engine:
def __init__(self, horsepower, type):
self.horsepower = horsepower
self.type = type
def show_engine(self):
print(f"Engine Type: {self.type}, Horsepower: {self.horsepower}")
class Car(Vehicle):
def __init__(self, brand, year, model, fuel_type, horsepower, engine_type):
super().__init__(brand, year)
self._model = model
self._fuel_type = fuel_type
self._engine = Engine(horsepower, engine_type)
# Containment: Car has an Engine
def show_details(self):
print("Car Details:")
super().show_details()
print(f"Model: {self._model}")
print(f"Fuel Type: {self._fuel_type}")
self._engine.show_engine() # Using contained Engine object's method
# Example usage
car = Car("Toyota", 2020, "Corolla", "Gas", 180, "V6")
car.show_details()
7. Destructor
class newClass():
def __del__(self):
print('object deleted.')
# create object
obj = newClass()
# delete object explicitly
del obj
# output
objecct deleted
8. No. of Underscore (Public vs Protected vs Private)
| Attribute Type | No Underscore (self.x) |
Single Underscore (self._x) |
Double Underscore (self.__x) |
|---|---|---|---|
| Access Level | Public | Protected (by convention) | Private (by convention, name-mangled) |
| Access from outside | Direct access (obj.x) |
Accessed with caution (obj._x) |
Cannot be accessed directly (obj.__x) |
| Name Mangling | No | No | Yes (_ClassName__x) |
| Intended Usage | For general use, available to all | For internal use within the class or subclasses (not truly private) | For internal use, harder to override or access from outside |
| Overriding Behavior | Can be easily overridden in subclasses | Can be easily overridden, but by convention it’s meant to be protected | Harder to accidentally override due to name mangling |
| Example | self.name = "Alice" |
self._protected = "secret" |
self.__private = "hidden" |
| Access Example | obj.name |
obj._protected |
obj._ClassName__private |