Functional vs Object-Oriented Programming: Python Concepts
Classified in Computers
Written on in
English with a size of 2.29 KB
Functional vs. Object-Oriented Programming
Object-Oriented Programming (OOP) models problems as objects containing data and methods that perform actions on that data. Functional Programming treats problems as a chain of functions evaluated to produce a result.
Code Output Analysis
- SQUARE [1, 4, 9]: []
- FIB FUNC: 0: 1, 1: 8, 2: 19, 3: 46
- HELLO F: The first prints “Hello world”. The second raises an error because
say_hello()is bound to an object but is called without an instance.
Python Methods Explained
A class method takes the class as the first argument. A static method takes no class or instance reference. An instance method takes an instance as an argument.
Intersection of N Lists
To find the intersection of multiple lists, use reduce with set.intersection:
from functools import reduce
in_list = [[1,2,3,4,5], [2,3,4,5,6], [3,4,5,6,7]]
result = reduce(set.intersection, map(set, in_list))
print(result) # Output: {3, 4, 5}Generator for Merging Sorted Sequences
def merge_sorted_lists(a, b):
i, j = 0, 0
while i < len(a) and j < len(b):
if a[i] < b[j]:
yield a[i]
i += 1
else:
yield b[j]
j += 1
yield from a[i:]
yield from b[j:]Refactoring Pi as a Class Method
class Circle:
pi = 3.14159
def __init__(self, center, radius):
self.c = center
self.radius = radius
def area(self):
return self.radius * self.radius * self.pi
@classmethod
def constant_pi(cls):
return cls.piUnderstanding Python Underscores
- _xx: Indicates a non-public member; should not be accessed directly as it is not part of the public API.
- __xx: Used to prevent method overriding by subclasses (name mangling).
- __xx__: Reserved for special Python methods (dunder methods) called internally by the interpreter.
Function Class Point Output
The output for the provided code is: 10 30 10 30