Python - Lambda, Functions, Class/Objects
Lambda
A lambda function in Python is a small, anonymous function that can take any number of arguments but only has one expression. The expression is executed, and its result is returned. Lambda functions are often used for short, one-time operations where a regular function definition would be too verbose.
Key characteristics of lambda functions:
Anonymous: They don't have a name unless explicitly assigned to a variable.
Concise: Defined in a single line.
Single Expression: Can only contain one expression.
Automatic Return: The result of the expression is automatically returned without a
return
statement.
Syntax:
lambda arguments: expression
lambda
is the keyword, arguments
are the input parameters, and expression
is the code to be executed.
Example:
add_ten = lambda a: a + 10
print(add_ten(5)) # Output: 15
This lambda function takes one argument a
, adds 10 to it, and returns the result.
Use cases for lambda functions:
Inline operations: Lambda functions are useful when you need a quick function for a short period1.
Higher-order functions: They are commonly used as arguments to higher-order functions like
map()
,filter()
, andsorted()
.numbers = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, numbers)) print(squared) # Output: [1, 4, 9, 16, 25]
Creating simple formulas: Lambda functions can be used to define simple formulas.
c_to_f = lambda c: (c * 9/5) + 32 print(c_to_f(0)) # Output: 32.0
Comparison with regular Python functions:
Name
Anonymous (unless assigned)
Named
Syntax
Single line
Multi-line
Return
Implicit
Explicit (return
statement)
Complexity
Simple expressions
Can contain complex logic
Lambda functions offer a way to write compact and simple functions, making your code more concise and readable in certain contexts. Here are some common use cases for lambda functions:
Sorting Lists with Custom Keys: Lambda functions can serve as custom key functions when sorting lists, enabling sorting based on a specific attribute or calculation.
Example: Sorting a list of students based on their grades.
Filtering Lists: Lambda functions can be used with the
filter()
function to filter a list based on a specific condition.Example: Filtering out even numbers from a list of integers.
Applying Transformations: They can be used with the
map()
function to apply a transformation to each element in a list.Example: Calculating the square of each number in a list.
Small, One-Time-Use Functions: Lambda functions are ideal for creating small functions that don’t need a full function definition.
Example: Finding the maximum of two numbers.
With
functools.reduce()
: Thereduce()
function from thefunctools
module can be used with a lambda function to apply a binary operation cumulatively to the elements in a list, reducing the list to a single value.Example: Calculating the product of all numbers in a list.
Implementing Simple Event Handlers: Lambda functions can create simple event handlers for user interface elements, like buttons in a GUI application.
Custom Comparison Functions: Lambda functions can be used to create custom comparison functions for data structures, such as heaps.
Concurrent Programming: They can be used to create simple, one-time-use functions when working with concurrent programming, such as with the
ThreadPoolExecutor
from theconcurrent.futures
module.Defining simple formulas: Lambda functions are also great for defining simple formulas.
Example: Convert Celsius to Fahrenheit.
Lambda functions are particularly useful in functional programming with functions like map()
and filter()
. They can make code more concise, readable, and efficient.
Functions
In Python, a function is a reusable block of code that performs a specific task. Functions help make code more modular and easier to manage.
Defining a Function
Syntax: Use the
def
keyword followed by the function name, parentheses()
, and a colon:
.def functionName(): # Function body
Body: The function body contains the code to be executed and is defined by indentation.
Parameters (Optional): You can pass arguments (parameters) inside the parentheses.
def functionName(arg1, arg2): # Function body
Calling a Function
Basic Call: To execute a function, write the function name followed by parentheses.
functionName()
With Arguments: If the function accepts arguments, provide the values inside the parentheses when calling the function.
functionName(valueForArg1, valueForArg2)
Return Keyword
Purpose: The
return
keyword exits the function and can send a value back to the callerdef multiplyNum(num1): return num1 * 8
Usage: The
return
statement can include an expression1. If noreturn
statement is provided, the function returnsNone
by default.
Example
def greet(name):
return f"Hello, {name}!"
message = greet("Alice")
print(message) # Output: Hello, Alice!
In this example, the function greet
takes a name as input and returns a greeting. The returned string is then stored in the message
variable and printed.
In Python, you can pass multiple arguments to a function in several ways. Here are the most common methods:
Positional Arguments
You can define a function with multiple parameters and pass arguments in the same order when calling the function.
Example:
def add(a, b, c):
return a + b + c
result = add(1, 2, 3) # Passes 1, 2, and 3 as arguments
print(result) # Output: 6
Using *args
for Variable-Length Arguments
*args
for Variable-Length ArgumentsIf you want to allow a function to accept any number of positional arguments, you can use the *args
syntax. This collects all extra positional arguments into a tuple.
Example:
def add_all(*args):
return sum(args)
result = add_all(1, 2, 3, 4) # Can pass any number of arguments
print(result) # Output: 10
Using **kwargs
for Keyword Arguments
**kwargs
for Keyword ArgumentsTo allow passing multiple keyword arguments (name-value pairs), use the **kwargs
syntax. This collects all extra keyword arguments into a dictionary.
Example:
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=30, city="New York")
This will output:
textname: Alice
age: 30
city: New York
Combining Positional and Keyword Arguments
You can combine both *args
and **kwargs
in a single function definition.
Example:
def mixed_args(arg1, arg2, *args, **kwargs):
print(f"arg1: {arg1}, arg2: {arg2}")
print("Additional args:", args)
print("Keyword args:", kwargs)
mixed_args(1, 2, 3, 4, name="Bob", age=25)
This will output:
textarg1: 1, arg2: 2
Additional args: (3, 4)
Keyword args: {'name': 'Bob', 'age': 25}
Unpacking Lists or Tuples
You can also pass a list or tuple as multiple arguments using the unpacking operator *
.
Example:
numbers = [1, 2, 3]
result = add(*numbers) # Unpacks the list into separate arguments
print(result) # Output: 6
These methods provide flexibility in how you define and call functions in Python, allowing you to handle varying numbers of inputs effectively.
Class and Object
In Python, classes and objects are fundamental concepts of object-oriented programming (OOP). They allow you to create structured and modular code by encapsulating data and behavior.
Class
A class is a blueprint for creating objects. It defines a set of attributes (data) and methods (functions) that the created objects will have. Classes allow you to group related functionalities together.
Defining a Class
To define a class, use the class
keyword followed by the class name and a colon. The class body is indented below the definition.
Example:
class Bike:
def __init__(self, name, gear):
self.name = name # Instance attribute
self.gear = gear # Instance attribute
def display_info(self):
return f"Name: {self.name}, Gears: {self.gear}"
In this example, Bike
is a class with an initializer method (__init__
) that sets the attributes name
and gear
. The method display_info
returns a string containing the bike's information.
Object
An object is an instance of a class. When you create an object, you are creating a specific instance that has its own unique data based on the class definition.
Creating an Object
You can create an object by calling the class as if it were a function.
Example:
# Create an object of the Bike class
bike1 = Bike("Mountain Bike", 5)
# Accessing attributes and methods
print(bike1.display_info()) # Output: Name: Mountain Bike, Gears: 5
Here, bike1
is an object of the Bike
class with specific values for its attributes. You can access its methods and attributes using the dot notation (e.g., bike1.display_info()
).
Summary
Class: A blueprint for creating objects that encapsulates data (attributes) and behavior (methods).
Object: An instance of a class that contains specific data defined by the class.
Example of Class and Object in Context
Here’s a complete example demonstrating both concepts:
class Car:
def __init__(self, make, model):
self.make = make # Instance attribute
self.model = model # Instance attribute
def start_engine(self):
return f"The engine of {self.make} {self.model} is now running."
# Creating objects
car1 = Car("Toyota", "Corolla")
car2 = Car("Honda", "Civic")
# Using methods
print(car1.start_engine()) # Output: The engine of Toyota Corolla is now running.
print(car2.start_engine()) # Output: The engine of Honda Civic is now running.
In this example, we define a Car
class with attributes for make
and model
, along with a method to start the engine. We then create two objects (car1
and car2
) from this class and call their methods to demonstrate how classes and objects work together in Python
Within a Python class, you can define different types of methods to implement various functionalities. The most common types are instance methods, class methods, and static methods1.
Instance Methods
Instance methods are the most commonly used methods within a class. They operate on specific instances (objects) of the class and can modify the object's state.
The first parameter of an instance method is conventionally named
self
, which refers to the instance of the class.Instance methods are accessed through class objects.
class Cricket: teamName = None # Class variable def setTeamName(self, name): # Instance method self.teamName = name def getTeamName(self): # Instance method return self.teamName c = Cricket() c.setTeamName('India') print(c.getTeamName()) # Output: India
Class Methods
Class methods are bound to the class itself rather than an instance of the class. They can access or modify the class state.
To define a class method, you use the
@classmethod
decorator before the method definition.The first parameter of a class method is conventionally named
cls
, which refers to the class itself.Class methods are often used to create factory methods, which return class objects for different use cases.
Class methods can be called using either
ClassName.method_name()
or through an object of the class.class Student: school_name = 'ABC School' # Class variable def __init__(self, name, age): self.name = name self.age = age @classmethod def change_school(cls, school_name): cls.school_name = school_name Student.change_school('XYZ School') print(Student.school_name) # Output: XYZ School
Static Methods
Static methods are general utility functions that perform tasks in isolation and don't have access to the class or instance state.
To define a static method, you use the
@staticmethod
decorator before the method definition1.Static methods do not take
self
orcls
as their first parameter.They are typically used when a method doesn't need to access any class-specific or instance-specific information
Static methods can be accessed using the class name or class objects
class Cricket: @staticmethod def utility(): print("This is a static method.") c1 = Cricket() c1.utility() # Output: This is a static method. Cricket.utility() # Output: This is a static method.
Here's a breakdown of the key differences between instance methods, class methods, and static methods in Python:
1. Instance Methods
Binding: Bound to an instance of the class. They require the creation of an object of the class before they can be called.
Access to Data: Can access and modify instance-specific data. They can access both class-level and object attributes.
Parameter: Requires
self
as the first parameter, which refers to the instance of the class.Usage: Used for instance-specific logic and operations that rely on the instance of the current class. They act on an object's attributes and can modify the object state by changing the value of instance variables.
2. Class Methods
Binding: Bound to the class itself, not to a specific instance.
Access to Data: Can access or modify the class state. They can only access class-level attributes.
Parameter: Requires
cls
as the first parameter, which refers to the class itself.Usage: Often used as factory methods that return a class object for different use cases. They can modify the class state by changing the value of a class variable, which applies across all class objects.
3. Static Methods
Binding: Not bound to either the instance of the class or the class itself.
Access to Data: Cannot access or modify instance or class data.
Parameter: Does not require
self
orcls
as the first parameter.Usage: Used for general utility functions that perform a task in isolation. They are helpful in utilities such as conversion from one type to another. They are useful for operations that don't require any data from an instance of the class.
Here's a table summarizing the key differences:
Binding
Instance-bound
Class-bound
Not bound
Access to Data
Accesses instance and class data
Accesses class-level data only
No access to instance or class data
Parameter
self
cls
No special first parameter
Usage
Instance-specific logic
Factory methods, modifying class state
General utility functions
Modification
Can modify the object state
Can modify the class state
Cannot modify the class or object state
Need of Object
Object of its class to be created before it can be called
No Object needed
Invoking
Using object reference
By using class reference
By using class reference
Last updated