0% found this document useful (0 votes)
10 views

W02.2- Python Concept

Uploaded by

KaNika TH11
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)
10 views

W02.2- Python Concept

Uploaded by

KaNika TH11
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
You are on page 1/ 14

REVIEW:

PYTHON PROGRAMMING
FUNDAMENTALS

Lecturer: SEK SOCHEAT


E-mail: socheat.sek@gmail.com MSIT - AEU (2023-2024)
Mobile: +855 17 879 967
TABLE OF CONTENTS
Python Programming Overview

1. Object-Oriented Programming 6. Concurrency and Parallelism


(OOP) 7. Type Hinting
2. Decorators 8. Advanced Data Structures
3. Generators and Iterators
9. Testing
4. Context Managers
5. Metaclasses

2
REVIEW PYTHON CONCEPTS
THE PYTHON REVIEW
Python concepts

• Python concepts expand your programming capabilities and allow you to write more efficient,
scalable, and maintainable code.
• Understanding and mastering these concepts will enable you to tackle more complex
programming challenges and write more sophisticated Python code.
Here’s a brief overview of some key advanced Python concepts:

1. Object-Oriented Programming (OOP) 6. Concurrency and Parallelism


2. Decorators
7. Type Hinting
3. Generators and Iterators
8. Advanced Data Structures
4. Context Managers
9. Testing
5. Metaclasses
4
THE PYTHON CONCEPTS
1. Object-Oriented Programming (OOP) Classes and Objects

• Classes and Objects: Define custom data class Animal:


structures with classes. Objects are instances def __init__(self, name):

of classes. self.name = name

• Inheritance: Create new classes from existing def speak(self):


ones, promoting code reuse. pass

• Polymorphism: Implement methods in class Dog(Animal):


different ways in different classes. def speak(self):
return f"{self.name} says Woof!"
• Encapsulation: Restrict access to methods
and variables, protecting object integrity. dog = Dog("Buddy")
5
print(dog.speak()) # Output: Buddy says Woof!
THE PYTHON CONCEPTS
2. Decorators
Function Decorators

def my_decorator(func):
def wrapper():
• Function Decorators: Modify print("Something is happening before the function is called.")
the behavior of a function or func()
print("Something is happening after the function is called.")
method using the @decorator
return wrapper
syntax.
# Output:
• Class Decorators: Modify or @my_decorator
Something is happening before the function is called.
def say_hello():
enhance classes in a similar way. Hello!
print("Hello!")
Something is happening after the function is called.

say_hello()
6
THE PYTHON CONCEPTS Output:

10
Generators
3. Generators and Iterators 9
import time 8
7
• Iterators: Objects that implement the ‘__iter__( )’ and ‘__next__( )’ 6
methods. def countdown(n): 5
while n >= 0: 4
• Generators: Functions that use ‘yield’ to return a sequence of values, yield n
3
providing a memory-efficient way to handle large datasets. 2
time.sleep(1) 1
• In Python, ‘yield’ is used in a function to make it a generator. n -= 1 Start Now…
• When the function is called, it returns a generator object instead of
executing the function's code immediately. for number in countdown(10):
• Each time the generator's ‘__next__( )’ method is called, the function if number == 0:
executes until it hits a ‘yield’ statement, which returns the yielded value print('Start Now...')
and pauses the function's state, allowing it to resume from where it left
off the next time ‘__next__( )’ is called.
• This makes it efficient for iterating over large datasets without storing else:
the entire dataset in memory. print(number)
7
THE PYTHON CONCEPTS
4. Context Managers
Using ‘with’ Statements
• Using with Statements:
Simplify resource
with open('example.txt', 'w') as file:
management, such as file
file.write('Hello, world!')
operations, by ensuring
proper acquisition and # Automatically closes the file when the block ends
release of resources.
8
THE PYTHON CONCEPTS
5. Metaclasses
Metaclasses

• Class of a Class: Control class MyMeta(type):


def __new__(cls, name, bases, dct):
the creation and behavior of print(f "Creating class {name}")
return super().__new__(cls, name, bases, dct)
classes themselves, allowing
for powerful and flexible class MyClass(metaclass = MyMeta):
pass
design patterns. # Output:

Creating class MyClass


9
THE PYTHON CONCEPTS
6. Concurrency and Parallelism
1). Threading

import threading
• Threading: Achieve concurrent execution using def print_numbers():
threads for I/O-bound tasks. for i in range(10):
print(i)
• Multiprocessing: Use multiple processes to achieve thread = threading.Thread(target=print_numbers)
parallelism, especially for CPU-bound tasks. thread.start()
2). Asyncio
thread.join()
import asyncio
• Asyncio: Write asynchronous code using ‘async’
async def main():
and ‘await’ for improved performance in I/O-bound print("Hello...")
await asyncio.sleep(1)
tasks.
print("...World!")

10 asyncio.run(main())
THE PYTHON CONCEPTS
7. Type Hinting Type Hinting

def greeting(name: str) -> str:


• Static Typing: Improve code readability return 'Hello ' + name

and debugging with type hints using the print(greeting("Alice"))

typing module. # Output: Hello Alice

Explain: def greeting(name: str) -> str:

• This line defines a function named ‘greeting’ that takes one parameter named name.
• ‘name: str’ indicates that the parameter name is expected to be a string.
• ‘-> str’ indicates that the function is expected to return a string.
11
THE PYTHON CONCEPTS
8. Advanced Data Structures
1). Collections Module

from collections import defaultdict


• Collections Module: Utilize
d = defaultdict(int)
specialized data structures like 2). Heapq
d['key1'] += 1
import heapq
‘defaultdict’, ‘Counter’, ‘deque’, print(d)

etc. # Output: numbers = [5, 1, 8, 3]


defaultdict(<class 'int'>, {'key1': 1}) heapq.heapify(numbers)

• Heapq and Bisect: Implement heapq.heappush(numbers, 2)


print(heapq.heappop(numbers))
priority queues and efficient array
# Output:
operations. 1
12
THE PYTHON CONCEPTS
9. Testing
Unit Testing
import unittest

• Unit Testing: Write tests using def add(a, b):


return a + b
frameworks like ‘unittest’, ‘pytest’,
class TestMath(unittest.TestCase):
or ‘doctest’ to ensure code reliability def test_add(self):
self.assertEqual(add(1, 2), 3)
and correctness. self.assertEqual(add(-1, 1), 0)
if __name__ == '__main__':
unittest.main()
13
Thank You!
If you have any questions, please reach me!

You might also like