Speed Run Functions and Classes
Video Tutorial
Functions in Python are reusable blocks of code that perform specific tasks, enhancing modularity and readability.
Functions and classes are fundamental building blocks in Python for creating reusable and modular code.
Functions
Functions are reusable blocks of code that perform specific tasks.
Defining a Function: Use the def
keyword.
def greet():
print("Hello, world!")
greet() # Output: "Hello, world!"
Functions with Parameters: Pass data into functions using parameters.
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # Output: "Hello, Alice!"
Returning Values: Use return
to output a value from a function.
def add(a, b):
return a + b
result = add(3, 5)
print(result) # Output: 8
Default Parameters: Assign default values to parameters.
def greet(name="world"):
print(f"Hello, {name}!")
greet() # Output: "Hello, world!"
greet("Bob") # Output: "Hello, Bob!"
Variable Number of Arguments: Use *args
and **kwargs
for flexible arguments.
def add(*args):
return sum(args)
print(add(1, 2, 3)) # Output: 6
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=30)
Classes
Classes are blueprints for creating objects (instances), encapsulating data and functions together.
Defining a Class: Use the class
keyword.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name}.")
person1 = Person("Alice", 30)
person1.greet() # Output: "Hello, my name is Alice."
Class Components:
- Constructor (
__init__
): Initializes new objects. - Instance Variables: Data unique to each instance (
self.name
,self.age
). - Methods: Functions defined within a class (
greet
).
Inheritance: Classes can inherit from other classes.
class Employee(Person):
def __init__(self, name, age, employee_id):
super().__init__(name, age)
self.employee_id = employee_id
def display_id(self):
print(f"My employee ID is {self.employee_id}.")
employee1 = Employee("Bob", 25, "E123")
employee1.greet() # Output: "Hello, my name is Bob."
employee1.display_id() # Output: "My employee ID is E123."
Encapsulation: Use underscores to indicate private variables (convention).
class BankAccount:
def __init__(self, balance):
self._balance = balance # Protected attribute
def deposit(self, amount):
self._balance += amount
def get_balance(self):
return self._balance
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # Output: 1500